List of usage examples for org.apache.http.client.methods HttpRequestBase abort
public void abort()
From source file:com.basho.riak.client.util.ClientHelper.java
/** * Perform and HTTP request and return the resulting response using the * internal HttpClient.//from www .j a v a 2s .c om * * @param bucket * Bucket of the object receiving the request. * @param key * Key of the object receiving the request or null if the request * is for a bucket. * @param httpMethod * The HTTP request to perform; must not be null. * @param meta * Extra HTTP headers to attach to the request. Query parameters * are ignored; they should have already been used to construct * <code>httpMethod</code> and query parameters. * @param streamResponse * If true, the connection will NOT be released. Use * HttpResponse.getHttpMethod().getResponseBodyAsStream() to get * the response stream; HttpResponse.getBody() will return null. * * @return The HTTP response returned by Riak from executing * <code>httpMethod</code>. * * @throws RiakIORuntimeException * If an error occurs during communication with the Riak server * (i.e. HttpClient threw an IOException) */ HttpResponse executeMethod(String bucket, String key, HttpRequestBase httpMethod, RequestMeta meta, boolean streamResponse) { if (meta != null) { Map<String, String> headers = meta.getHeaders(); for (String header : headers.keySet()) { httpMethod.addHeader(header, headers.get(header)); } Map<String, String> queryParams = meta.getQueryParamMap(); if (!queryParams.isEmpty()) { URI originalURI = httpMethod.getURI(); List<NameValuePair> currentQuery = URLEncodedUtils.parse(originalURI, CharsetUtils.UTF_8.name()); List<NameValuePair> newQuery = new LinkedList<NameValuePair>(currentQuery); for (Map.Entry<String, String> qp : queryParams.entrySet()) { newQuery.add(new BasicNameValuePair(qp.getKey(), qp.getValue())); } // For this, HC4.1 authors, I hate you URI newURI; try { newURI = URIUtils.createURI(originalURI.getScheme(), originalURI.getHost(), originalURI.getPort(), originalURI.getPath(), URLEncodedUtils.format(newQuery, "UTF-8"), null); } catch (URISyntaxException e) { throw new RiakIORuntimeException(e); } httpMethod.setURI(newURI); } } HttpEntity entity; try { org.apache.http.HttpResponse response = httpClient.execute(httpMethod); int status = 0; if (response.getStatusLine() != null) { status = response.getStatusLine().getStatusCode(); } Map<String, String> headers = ClientUtils.asHeaderMap(response.getAllHeaders()); byte[] body = null; InputStream stream = null; entity = response.getEntity(); if (streamResponse) { stream = entity.getContent(); } else { if (null != entity) { body = EntityUtils.toByteArray(entity); } } if (!streamResponse) { EntityUtils.consume(entity); } return new DefaultHttpResponse(bucket, key, status, headers, body, stream, response, httpMethod); } catch (IOException e) { httpMethod.abort(); return toss(new RiakIORuntimeException(e)); } }
From source file:com.basho.riak.client.http.util.ClientHelper.java
/** * Perform and HTTP request and return the resulting response using the * internal HttpClient./*from w ww. j a v a2 s . c o m*/ * * @param bucket * Bucket of the object receiving the request. * @param key * Key of the object receiving the request or null if the request * is for a bucket. * @param httpMethod * The HTTP request to perform; must not be null. * @param meta * Extra HTTP headers to attach to the request. Query parameters * are ignored; they should have already been used to construct * <code>httpMethod</code> and query parameters. * @param streamResponse * If true, the connection will NOT be released. Use * HttpResponse.getHttpMethod().getResponseBodyAsStream() to get * the response stream; HttpResponse.getBody() will return null. * * @return The HTTP response returned by Riak from executing * <code>httpMethod</code>. * * @throws RiakIORuntimeException * If an error occurs during communication with the Riak server * (i.e. HttpClient threw an IOException) */ HttpResponse executeMethod(String bucket, String key, HttpRequestBase httpMethod, RequestMeta meta, boolean streamResponse) { if (meta != null) { Map<String, String> headers = meta.getHeaders(); for (String header : headers.keySet()) { httpMethod.addHeader(header, headers.get(header)); } Map<String, String> queryParams = meta.getQueryParamMap(); if (!queryParams.isEmpty()) { URI originalURI = httpMethod.getURI(); List<NameValuePair> currentQuery = URLEncodedUtils.parse(originalURI, CharsetUtils.UTF_8.name()); List<NameValuePair> newQuery = new LinkedList<NameValuePair>(currentQuery); for (Map.Entry<String, String> qp : queryParams.entrySet()) { newQuery.add(new BasicNameValuePair(qp.getKey(), qp.getValue())); } // For this, HC4.1 authors, I hate you URI newURI; try { newURI = new URIBuilder(originalURI).setQuery(URLEncodedUtils.format(newQuery, "UTF-8")) .build(); } catch (URISyntaxException e) { e.printStackTrace(); throw new RiakIORuntimeException(e); } httpMethod.setURI(newURI); } } HttpEntity entity = null; try { org.apache.http.HttpResponse response = httpClient.execute(httpMethod); int status = 0; if (response.getStatusLine() != null) { status = response.getStatusLine().getStatusCode(); } Map<String, String> headers = ClientUtils.asHeaderMap(response.getAllHeaders()); byte[] body = null; InputStream stream = null; entity = response.getEntity(); if (streamResponse) { stream = entity.getContent(); } else { if (null != entity) { body = EntityUtils.toByteArray(entity); } } key = extractKeyFromResponseIfItWasNotAlreadyProvided(key, response); return new DefaultHttpResponse(bucket, key, status, headers, body, stream, response, httpMethod); } catch (IOException e) { httpMethod.abort(); return toss(new RiakIORuntimeException(e)); } finally { if (!streamResponse && entity != null) { try { EntityUtils.consume(entity); } catch (IOException e) { // NO-OP } } } }
From source file:org.cloudifysource.restclient.GSRestClient.java
/** * Executes the given HTTP request and analyzes the response. Successful responses are expected to be formatted as * json strings, and are converted to a Map<String, Object> object. The map can use these keys: "status" * (success/error), "error"(reason code), "error_args" and "response". * <p/>/* www. jav a 2s.c o m*/ * Errors of all types (IO, HTTP, rest etc.) are reported through an ErrorStatusException (RestException). * * @param httpMethod * The HTTP request to perform. * @return An object, the response body received from the rest service * @throws RestException * Reporting errors of all types (IO, HTTP, rest etc.) */ private Map<String, Object> readHttpAdminMethod(final HttpRequestBase httpMethod) throws RestException { InputStream instream = null; URI uri = httpMethod.getURI(); try { final HttpResponse response = httpClient.execute(httpMethod); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != CloudifyConstants.HTTP_STATUS_CODE_OK) { final String message = uri + " response (code " + statusCode + ") " + statusLine.toString(); if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, message); } throw new RestException(message); } final HttpEntity entity = response.getEntity(); if (entity == null) { final ErrorStatusException e = new ErrorStatusException(REASON_CODE_COMM_ERR, uri, MSG_RESPONSE_ENTITY_NULL); logger.log(Level.FINE, uri + MSG_RESPONSE_ENTITY_NULL, e); throw e; } instream = entity.getContent(); final String responseBody = StringUtils.getStringFromStream(instream); logger.finer(uri + MSG_HTTP_GET_RESPONSE + responseBody); final Map<String, Object> responseMap = GSRestClient.jsonToMap(responseBody); return responseMap; } catch (final ClientProtocolException e) { logger.log(Level.FINE, uri + MSG_REST_API_ERR, e); throw new ErrorStatusException(e, REASON_CODE_COMM_ERR, uri, MSG_REST_API_ERR); } catch (final IOException e) { logger.log(Level.FINE, uri + MSG_REST_API_ERR, e); throw new ErrorStatusException(e, REASON_CODE_COMM_ERR, uri, MSG_REST_API_ERR); } finally { if (instream != null) { try { instream.close(); } catch (final IOException e) { } } httpMethod.abort(); } }
From source file:org.atricore.idbus.idojos.gateinidentitystore.GateInBindIdentityStore.java
private boolean executeRemoteCall(String authUrl) throws Exception { if (log.isDebugEnabled()) log.debug("Starting remote call using HTTP client\n[" + authUrl + "]"); InputStream instream = null;// ww w. j a va 2s .c o m HttpRequestBase httpReq = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); if (log.isTraceEnabled()) log.trace("Client OK"); httpReq = new HttpGet(authUrl); if (log.isTraceEnabled()) log.trace("Method OK"); HttpResponse httpRes = httpClient.execute(httpReq); int status = httpRes.getStatusLine().getStatusCode(); if (log.isTraceEnabled()) log.trace("Client execution OK"); if (log.isTraceEnabled()) log.trace("Response OK"); // Get hold of the response entity HttpEntity entity = httpRes.getEntity(); if (entity != null) { instream = entity.getContent(); // If the response does not enclose an entity, there is no need byte[] buff = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); String response = null; // Just ignore the content ... // should we do something with this ?! int r = instream.read(buff); int total = r; while (r > 0) { baos.write(buff, 0, r); r = instream.read(buff); total += r; } response = baos.toString(); if (total > 0) log.debug("Read response content size : " + total + " [" + response + "] "); switch (status) { case 200: if (response != null && Boolean.parseBoolean(response)) { return true; } break; default: log.warn("Received invalid HTTP status " + status + " for " + authUrl); } return false; } else { // Not authenticated log.warn("No response body received for " + authUrl); return false; } } catch (IOException ex) { // In case of an IOException the connection will be released // back to the connection manager automatically throw ex; } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection immediately. if (httpReq != null) { try { httpReq.abort(); } catch (Exception e) { log.error(e.getMessage(), e); } } } finally { // Closing the input stream will trigger connection release try { instream.close(); } catch (Exception ignore) { // Ignore this ... } } return false; }
From source file:ro.zg.netcell.datasources.executors.http.HttpCommandExecutor.java
public HttpCommandResponse executeCommand(CommandContext commandContext) throws Exception { HttpClient httpClient = (HttpClient) commandContext.getConnectionManager().getConnection(); ScriptDaoCommand command = commandContext.getCommand(); String method = (String) command.getArgument("method"); String url = (String) command.getArgument("url"); /* encode the url passed on the http request */ // URI requestUri = new URI(url); // requestUri = URIUtils.createURI(requestUri.getScheme(), requestUri.getHost(), requestUri.getPort(), // requestUri.getPath(), URLEncoder.encode(requestUri.getQuery(),HTTP.DEFAULT_PROTOCOL_CHARSET), // requestUri.getFragment()); String encodedUrl = URLEncoder.encode(url, HTTP.DEFAULT_PROTOCOL_CHARSET); boolean returnHeaders = false; Object rh = command.getArgument("returnHeaders"); if (rh != null) { returnHeaders = (Boolean) rh; }/*from www . j a v a 2 s .com*/ HttpRequestBase request = null; if ("GET".equals(method)) { request = new HttpGet(encodedUrl); } else if ("POST".equals(method)) { HttpPost post = new HttpPost(encodedUrl); String content = (String) command.getArgument("content"); if (content != null) { post.setEntity(new StringEntity(content)); } request = post; } else if ("HEAD".equals(method)) { request = new HttpHead(encodedUrl); } Map<String, String> requestHeaders = (Map) command.getArgument("requestHeaders"); if (requestHeaders != null) { for (Map.Entry<String, String> entry : requestHeaders.entrySet()) { request.setHeader(entry.getKey(), entry.getValue()); } } HttpContext localContext = new BasicHttpContext(); HttpEntity responseEntity = null; HttpCommandResponse commandResponse = new HttpCommandResponse(); try { HttpResponse response = httpClient.execute(request, localContext); responseEntity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); commandResponse.setStatusCode(statusLine.getStatusCode()); commandResponse.setProtocol(statusLine.getProtocolVersion().getProtocol()); commandResponse.setReasonPhrase(statusLine.getReasonPhrase()); commandResponse.setRequestUrl(url); HttpRequest actualRequest = (HttpRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost targetHost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); commandResponse.setTargetUrl(targetHost.toURI() + actualRequest.getRequestLine().getUri()); if (returnHeaders) { Map<String, String> headers = new HashMap<String, String>(); for (Header h : response.getAllHeaders()) { headers.put(h.getName().toLowerCase(), h.getValue().toLowerCase()); } commandResponse.setHeaders(headers); } if (responseEntity != null) { long responseLength = responseEntity.getContentLength(); String responseContent = EntityUtils.toString(responseEntity, HTTP.UTF_8); if (responseLength == -1) { responseLength = responseContent.length(); } commandResponse.setLength(responseLength); commandResponse.setContent(responseContent); } } finally { if (responseEntity != null) { responseEntity.consumeContent(); } else { request.abort(); } } return commandResponse; }
From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java
private <T> T executeRequest(final HttpRequestBase httpRequest, final HttpClientRequest<T> httpClientRequest) throws IOException { final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, setFollowRedirects(params, httpClientRequest)); httpClient.getCookieSpecs().register(NessCookieSpecFactory.NESS_COOKIE_POLICY, new NessCookieSpecFactory()); httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(retries, false)); contributeCookies(httpClient, httpClientRequest); contributeParameters(httpClient, httpRequest, httpClientRequest); contributeHeaders(httpRequest, httpClientRequest); contributeVirtualHost(httpRequest, httpClientRequest); contributeAuthentication(httpClient, httpClientRequest); try {/* w w w .ja v a 2s . co m*/ final HttpContext httpContext = new BasicHttpContext(); final HttpResponse httpResponse = httpClient.execute(httpRequest, httpContext); final HttpClientResponseHandler<T> responseHandler = httpClientRequest.getHttpHandler(); try { final HttpClientResponse internalResponse = new InternalResponse(httpRequest, httpResponse); HttpClientResponse response = internalResponse; if (CollectionUtils.isNotEmpty(httpClientObservers)) { LOG.trace("Executing Observers"); for (HttpClientObserver observer : httpClientObservers) { response = observer.onResponseReceived(response); } if (response != internalResponse) { LOG.trace("Response was modified by Observers!"); } } if (responseHandler != null) { LOG.trace("Executing Response Handler"); return responseHandler.handle(response); } else { LOG.debug("No response handler found, discarding response."); return null; } } finally { // Make sure that the content has definitely been consumed. Otherwise, // keep-alive does not work. EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException ioe) { LOG.debug(ioe, "Aborting Request!"); httpRequest.abort(); throw ioe; } catch (RuntimeException re) { LOG.debug(re, "Aborting Request!"); httpRequest.abort(); throw re; } }
From source file:net.paissad.minus.utils.HttpClientUtils.java
/** * Convenience method for sending HTTP requests. * <b><span style="color:red">Note</span></b>: This method is intended to be * used internally, not by end-users./*from w w w .ja v a 2s . co m*/ * * @param baseURL - <b>Example</b>: http://minus.com/api * @param parametersBody - The parameters (name => value pairs) to pass to * the request. * @param sessionId - If <tt>null</tt> or empty, then create and use a new * session, otherwise, use the specified session_id (which is * stored in a cookie). * @param requestType * @param additionalRequestHeaders - * @param expectedResponseType * @return The response retrieved from Minus API. * @throws MinusException */ private static MinusHttpResponse sendRequest(final String baseURL, final Map<String, String> parametersBody, final String sessionId, final RequestType requestType, final Header[] additionalRequestHeaders, final ExpectedResponseType expectedResponseType) throws MinusException { DefaultHttpClient client = null; HttpRequestBase request = null; InputStream responseContent = null; boolean errorOccured = false; try { if (requestType == RequestType.GET) { request = new HttpGet(baseURL); if (parametersBody != null && !parametersBody.isEmpty()) { request = appendParametersToRequest(request, parametersBody); } } else if (requestType == RequestType.POST) { UrlEncodedFormEntity encodedEntity = new UrlEncodedFormEntity(getHttpParamsFromMap(parametersBody), HTTP.UTF_8); request = new HttpPost(baseURL); ((HttpPost) request).setEntity(encodedEntity); } else { throw new MinusException("The method (" + requestType + ") is unknown, weird ..."); } request.addHeader(new BasicHeader("User-Agent", APP_USER_AGENT)); if (additionalRequestHeaders != null && additionalRequestHeaders.length > 0) { for (Header aHeader : additionalRequestHeaders) { request.addHeader(aHeader); } } client = new DefaultHttpClient(); client.setHttpRequestRetryHandler(new MinusHttpRequestRetryHandler()); client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true); client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); CookieStore cookieStore = new BasicCookieStore(); Cookie sessionCookie = null; if (sessionId != null && !sessionId.trim().isEmpty()) { sessionCookie = new BasicClientCookie2(MINUS_COOKIE_NAME, sessionId); ((BasicClientCookie2) sessionCookie).setPath("/"); ((BasicClientCookie2) sessionCookie).setDomain(MINUS_DOMAIN_NAME); ((BasicClientCookie2) sessionCookie).setVersion(0); cookieStore.addCookie(sessionCookie); } client.setCookieStore(cookieStore); HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // Execute the request ... pass local context as a parameter HttpResponse resp = client.execute(request, localContext); // Let's update the cookie have the name 'sessionid' for (Cookie aCookie : client.getCookieStore().getCookies()) { if (aCookie.getName().equals(MINUS_COOKIE_NAME)) { sessionCookie = aCookie; break; } } Object result = null; int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity entity = resp.getEntity(); if (entity != null) { if (expectedResponseType == ExpectedResponseType.STRING) { result = EntityUtils.toString(entity); EntityUtils.consume(entity); } else if (expectedResponseType == ExpectedResponseType.HTTP_ENTITY) { result = entity; } } } else { // The response code is not OK. StringBuilder errMsg = new StringBuilder(); errMsg.append("HTTP ").append(requestType).append(" failed => ").append(resp.getStatusLine()); if (request != null) { errMsg.append(" : ").append(request.getURI()); } throw new MinusException(errMsg.toString()); } return new MinusHttpResponse(result, sessionCookie); } catch (Exception e) { errorOccured = true; if (request != null) { request.abort(); } String errMsg = "Error while executing the HTTP " + requestType + " request : " + e.getMessage(); throw new MinusException(errMsg, e); } finally { if (client != null) { // We must not close the client is the expected response is an // InputStream. Indeed, if ever we close the client, we won't be // able to read the response because of SocketException. if (errorOccured) { client.getConnectionManager().shutdown(); } else if (expectedResponseType != ExpectedResponseType.HTTP_ENTITY) { client.getConnectionManager().shutdown(); } } CommonUtils.closeAllStreamsQuietly(responseContent); } }
From source file:org.cloudifysource.restclient.GSRestClient.java
/** * This method executes the given Http request and analyzes the response. Successful responses are expected to be * formatted as json strings, and are converted to a Map<String, Object> object. In this map these keys can be * expected: "status" (success/error), "error"(reason code), "error_args" and "response". * <p/>/*www . j av a 2s . co m*/ * Errors of all types (IO, Http, rest etc.) are reported through an ErrorStatusException. * * @param httpMethod * The http request to perform. * @param responseJsonKey * specify a key for a response attribute to be returned, null means return the entire response * @return An object, the response body received from the rest service * @throws ErrorStatusException * Reporting errors of all types (IO, HTTP, rest etc.) */ private Object executeHttpMethod(final HttpRequestBase httpMethod, final String responseJsonKey) throws ErrorStatusException { String responseBody; try { final HttpResponse response = httpClient.execute(httpMethod); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != CloudifyConstants.HTTP_STATUS_CODE_OK) { final String reasonPhrase = response.getStatusLine().getReasonPhrase(); if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, httpMethod.getURI() + MSG_RESPONSE_CODE + statusCode + ", " + MSG_RESPONSE_REASON_PHRASE + ": " + reasonPhrase); } responseBody = getResponseBody(response, httpMethod); if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, httpMethod.getURI() + " response body " + responseBody); } if (statusCode == CloudifyConstants.HTTP_STATUS_NOT_FOUND) { throw new ErrorStatusException("URL_not_found", httpMethod.getURI()); } else if (statusCode == CloudifyConstants.HTTP_STATUS_ACCESS_DENIED) { throw new ErrorStatusException(CloudifyErrorMessages.NO_PERMISSION_ACCESS_DENIED.getName(), httpMethod.getURI()); } else if (statusCode == CloudifyConstants.HTTP_STATUS_UNAUTHORIZED) { throw new ErrorStatusException(CloudifyErrorMessages.UNAUTHORIZED.getName(), reasonPhrase, httpMethod.getURI()); } final Map<String, Object> errorMap = GSRestClient.jsonToMap(responseBody); final String status = (String) errorMap.get(STATUS_KEY); if (ERROR.equals(status)) { final String reason = (String) errorMap.get(ERROR); @SuppressWarnings("unchecked") final List<Object> reasonsArgs = (List<Object>) errorMap.get(ERROR_ARGS); final ErrorStatusException e = new ErrorStatusException(reason, reasonsArgs != null ? reasonsArgs.toArray() : null); if (errorMap.containsKey(VERBOSE)) { e.setVerboseData((String) errorMap.get(VERBOSE)); } logger.log(Level.FINE, reason, e); throw e; } } responseBody = getResponseBody(response, httpMethod); final Map<String, Object> responseMap = GSRestClient.jsonToMap(responseBody); return responseJsonKey != null ? responseMap.get(RESPONSE_KEY) : responseMap; } catch (final IOException e) { logger.log(Level.INFO, httpMethod.getURI() + MSG_REST_API_ERR, e); throw new ErrorStatusException(e, REASON_CODE_COMM_ERR, httpMethod.getURI(), e.getMessage()); } finally { httpMethod.abort(); } }