List of usage examples for org.apache.commons.httpclient HttpMethodBase releaseConnection
@Override public void releaseConnection()
From source file:org.review_board.ereviewboard.core.client.ReviewboardHttpClient.java
private byte[] executeMethodForBytes(HttpMethodBase request, IProgressMonitor monitor) throws ReviewboardException { monitor = Policy.monitorFor(monitor); ensureIsLoggedIn(monitor);/*from w w w.ja v a 2 s. c om*/ try { monitor.beginTask("Executing request", IProgressMonitor.UNKNOWN); executeRequest(request, monitor); return getResponseBodyAsByteArray(request, monitor); } finally { request.releaseConnection(); monitor.done(); } }
From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java
private void abortAndRelease(HttpMethodBase method) { if (method != null) { method.abort(); method.releaseConnection(); } }
From source file:org.sonar.wsclient.connectors.HttpClient3Connector.java
private String executeRequest(HttpMethodBase method) { String json = null;//from ww w . jav a 2 s .com try { httpClient.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { json = getResponseBodyAsString(method); } else if (method.getStatusCode() != HttpStatus.SC_NOT_FOUND) { throw new ConnectionException("HTTP error: " + method.getStatusCode() + ", msg: " + method.getStatusText() + ", query: " + method); } } catch (HttpException e) { throw new ConnectionException("Query: " + method, e); } catch (IOException e) { throw new ConnectionException("Query: " + method, e); } finally { if (method != null) { method.releaseConnection(); } } return json; }
From source file:org.sonarqube.ws.connectors.HttpClient3Connector.java
/** * Reauest execution// w w w . jav a2 s. c om * * @param method * method * @return String result */ private String executeRequest(HttpMethodBase method) throws ConnectionException { String json = null; try { httpClient.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { json = getResponseBodyAsString(method); } else if (method.getStatusCode() != HttpStatus.SC_NOT_FOUND) { throw new ConnectionException("HTTP error: " + method.getStatusCode() + ", msg: " + method.getStatusText() + ", query: " + method); } } catch (IOException e) { throw new ConnectionException("Query: " + method, e); } finally { if (method != null) { method.releaseConnection(); } } return json; }
From source file:org.sonatype.nexus.integrationtests.nexus4257.Nexus4257CookieVerificationIT.java
private int executeAndRelease(HttpClient httpClient, HttpMethodBase method) throws IOException { int status = 0; try {//from w ww .ja v a2 s . co m status = httpClient.executeMethod(method); } finally { method.releaseConnection(); } return status; }
From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java
@Override protected boolean checkRemoteAvailability(long newerThen, ProxyRepository repository, ResourceStoreRequest request, boolean isStrict) throws RemoteStorageException { URL remoteURL = getAbsoluteUrlFromBase(repository, request); HttpMethodBase method = new HeadMethod(remoteURL.toString()); int response = HttpStatus.SC_BAD_REQUEST; // artifactory hack, it pukes on HEAD so we will try with GET if HEAD fails boolean doGet = false; try {// w w w . j a va2s. c o m response = executeMethod(repository, request, method, remoteURL); } catch (RemoteStorageException e) { // If HEAD failed, attempt a GET. Some repos may not support HEAD method doGet = true; getLogger().debug("HEAD method failed, will attempt GET. Exception: " + e.getMessage(), e); } finally { method.releaseConnection(); // HEAD returned error, but not exception, try GET before failing if (!doGet && response != HttpStatus.SC_OK) { doGet = true; getLogger().debug("HEAD method failed, will attempt GET. Status: " + response); } } if (doGet) { // create a GET method = new GetMethod(remoteURL.toString()); try { // execute it response = executeMethod(repository, request, method, remoteURL); } finally { // and release it immediately method.releaseConnection(); } } // if we are not strict and remote is S3 if (!isStrict && isRemotePeerAmazonS3Storage(repository)) { // if we are relaxed, we will accept any HTTP response code below 500. This means anyway the HTTP // transaction succeeded. This method was never really detecting that the remoteUrl really denotes a root of // repository (how could we do that?) // this "relaxed" check will help us to "pass" S3 remote storage. return response >= HttpStatus.SC_OK && response <= HttpStatus.SC_INTERNAL_SERVER_ERROR; } else { // non relaxed check is strict, and will select only the OK response if (response == HttpStatus.SC_OK) { // we have it // we have newer if this below is true return makeDateFromHeader(method.getResponseHeader("last-modified")) > newerThen; } else if ((response >= HttpStatus.SC_MULTIPLE_CHOICES && response < HttpStatus.SC_BAD_REQUEST) || response == HttpStatus.SC_NOT_FOUND) { return false; } else { throw new RemoteStorageException("Unexpected response code while executing " + method.getName() + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]. Expected: \"SUCCESS (200)\". Received: " + response + " : " + HttpStatus.getStatusText(response)); } } }
From source file:org.springfield.mojo.http.HttpHelper.java
/** * Sends a standard HTTP request to the specified URI using the determined method. * Attaches the content, uses the specified content type, sets cookies, timeout and * request headers/*from w w w .j a va 2 s .co m*/ * * @param method - the request method * @param uri - the uri to request * @param body - the content * @param contentType - the content type * @param cookies - cookies * @param timeout - timeout in milliseconds * @param charSet - the character set * @param requestHeaders - extra user defined headers * @return response */ public static Response sendRequest(String method, String uri, String body, String contentType, String cookies, int timeout, String charSet, Map<String, String> requestHeaders) { // http client HttpClient client = new HttpClient(); // method HttpMethodBase reqMethod = null; if (method.equals(HttpMethods.PUT)) { reqMethod = new PutMethod(uri); } else if (method.equals(HttpMethods.POST)) { reqMethod = new PostMethod(uri); } else if (method.equals(HttpMethods.GET)) { if (body != null) { // hack to be able to send a request body with a get (only if required) reqMethod = new PostMethod(uri) { public String getName() { return "GET"; } }; } else { reqMethod = new GetMethod(uri); } } else if (method.equals(HttpMethods.DELETE)) { if (body != null) { // hack to be able to send a request body with a delete (only if required) reqMethod = new PostMethod(uri) { public String getName() { return "DELETE"; } }; } else { reqMethod = new DeleteMethod(uri); } } else if (method.equals(HttpMethods.HEAD)) { reqMethod = new HeadMethod(uri); } else if (method.equals(HttpMethods.TRACE)) { reqMethod = new TraceMethod(uri); } else if (method.equals(HttpMethods.OPTIONS)) { reqMethod = new OptionsMethod(uri); } // add request body if (body != null) { try { RequestEntity entity = new StringRequestEntity(body, contentType, charSet); ((EntityEnclosingMethod) reqMethod).setRequestEntity(entity); reqMethod.setRequestHeader("Content-type", contentType); } catch (Exception e) { e.printStackTrace(); } } // add cookies if (cookies != null) { reqMethod.addRequestHeader("Cookie", cookies); } // add custom headers if (requestHeaders != null) { for (Map.Entry<String, String> header : requestHeaders.entrySet()) { String name = header.getKey(); String value = header.getValue(); reqMethod.addRequestHeader(name, value); } } Response response = new Response(); // do request try { if (timeout != -1) { client.getParams().setSoTimeout(timeout); } int statusCode = client.executeMethod(reqMethod); response.setStatusCode(statusCode); } catch (Exception e) { e.printStackTrace(); } // read response try { InputStream instream = reqMethod.getResponseBodyAsStream(); ByteArrayOutputStream outstream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int len; while ((len = instream.read(buffer)) > 0) { outstream.write(buffer, 0, len); } String resp = new String(outstream.toByteArray(), reqMethod.getResponseCharSet()); response.setResponse(resp); //set content length long contentLength = reqMethod.getResponseContentLength(); response.setContentLength(contentLength); //set character set String respCharSet = reqMethod.getResponseCharSet(); response.setCharSet(respCharSet); //set all headers Header[] headers = reqMethod.getResponseHeaders(); response.setHeaders(headers); } catch (Exception e) { e.printStackTrace(); } // release connection reqMethod.releaseConnection(); // return return response; }
From source file:org.svenk.redmine.core.client.AbstractRedmineClient.java
protected <T extends Object> T executeMethod(HttpMethodBase method, IRedmineResponseParser<T> parser, IProgressMonitor monitor, int... expectedSC) throws RedmineException { monitor = Policy.monitorFor(monitor); method.setFollowRedirects(false);/*from w w w . j a v a 2 s .co m*/ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor); T response = null; try { int sc = executeMethod(method, hostConfiguration, monitor); if (parser != null && expectedSC != null) { boolean found = false; for (int i : expectedSC) { if (i == sc) { InputStream input = WebUtil.getResponseBodyAsStream(method, monitor); try { found = true; response = parser.parseResponse(input, sc); } finally { input.close(); } break; } } if (!found) { String msg = Messages.AbstractRedmineClient_UNEXPECTED_RESPONSE_CODE; msg = String.format(msg, sc, method.getPath(), method.getName()); IStatus status = new Status(IStatus.ERROR, RedmineCorePlugin.PLUGIN_ID, msg); StatusHandler.fail(status); throw new RedmineStatusException(status); } } } catch (RedmineErrorException e) { IStatus status = RedmineCorePlugin.toStatus(e, null); StatusHandler.fail(status); throw new RedmineStatusException(status); } catch (IOException e) { IStatus status = RedmineCorePlugin.toStatus(e, null); StatusHandler.log(status); throw new RedmineStatusException(status); } finally { method.releaseConnection(); } return response; }
From source file:org.tinygroup.httpvisit.impl.HttpVisitorImpl.java
String execute(HttpMethodBase method) { try {//from ww w. ja va 2 s .co m if (client == null) { init(); } LOGGER.logMessage(LogLevel.DEBUG, "?:{}", method.getURI().toString()); if (!("ISO-8859-1").equals(requestCharset)) { method.addRequestHeader("Content-Type", "text/html; charset=" + requestCharset); } method.setDoAuthentication(authEnabled); int iGetResultCode = client.executeMethod(method); if (iGetResultCode == HttpStatus.SC_OK) { LOGGER.logMessage(LogLevel.DEBUG, "?"); Header responseHeader = method.getResponseHeader("Content-Encoding"); if (responseHeader != null) { String acceptEncoding = responseHeader.getValue(); if (acceptEncoding != null && ("gzip").equals(acceptEncoding)) { //gzip? ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( method.getResponseBody()); GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream); return IOUtils.readFromInputStream(gzipInputStream, responseCharset); } } return new String(method.getResponseBody(), responseCharset); } LOGGER.logMessage(LogLevel.ERROR, "{}", method.getStatusLine().toString()); throw new RuntimeException(method.getStatusLine().toString()); } catch (Exception e) { LOGGER.logMessage(LogLevel.DEBUG, "{}", e.getMessage()); throw new RuntimeException(e); } finally { method.releaseConnection(); } }
From source file:org.wso2.carbon.appfactory.common.util.MutualAuthHttpClient.java
/** * Send rest request.//from w ww . j a v a 2s . c o m * * @param httpClient client object * @param method method type * @throws org.wso2.carbon.appfactory.common.AppFactoryException */ private static ServerResponse send(HttpClient httpClient, HttpMethodBase method) throws AppFactoryException { int responseCode; String responseString = null; try { responseCode = httpClient.executeMethod(method); } catch (IOException e) { String msg = "Error occurred while executing method " + method.getName(); log.error(msg, e); throw new AppFactoryException(msg, e); } try { responseString = method.getResponseBodyAsString(); } catch (IOException e) { String msg = "error while getting response as String for " + method.getName(); log.error(msg, e); throw new AppFactoryException(msg, e); } finally { method.releaseConnection(); } if (log.isDebugEnabled()) { log.debug("Response id: " + responseCode + " message: " + responseString); } return new ServerResponse(responseString, responseCode); }