List of usage examples for org.apache.http.nio.client.methods HttpAsyncMethods create
public static HttpAsyncRequestProducer create(final HttpUriRequest request)
From source file:httpasync.QuickStart.java
public static void main(String[] args) throws Exception { CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); try {// w ww . ja va 2 s .c o m // Start the client httpclient.start(); // Execute request final HttpGet request1 = new HttpGet("http://www.apache.org/"); Future<HttpResponse> future = httpclient.execute(request1, null); // and wait until response is received HttpResponse response1 = future.get(); System.out.println(request1.getRequestLine() + "->" + response1.getStatusLine()); // One most likely would want to use a callback for operation result final CountDownLatch latch1 = new CountDownLatch(1); final HttpGet request2 = new HttpGet("http://www.apache.org/"); httpclient.execute(request2, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response2) { latch1.countDown(); System.out.println(request2.getRequestLine() + "->" + response2.getStatusLine()); } @Override public void failed(final Exception ex) { latch1.countDown(); System.out.println(request2.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch1.countDown(); System.out.println(request2.getRequestLine() + " cancelled"); } }); latch1.await(); // In real world one most likely would want also want to stream // request and response body content final CountDownLatch latch2 = new CountDownLatch(1); final HttpGet request3 = new HttpGet("http://www.apache.org/"); HttpAsyncRequestProducer producer3 = HttpAsyncMethods.create(request3); AsyncCharConsumer<HttpResponse> consumer3 = new AsyncCharConsumer<HttpResponse>() { HttpResponse response; @Override protected void onResponseReceived(final HttpResponse response) { this.response = response; } @Override protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException { // Do something useful } @Override protected void releaseResources() { } @Override protected HttpResponse buildResult(final HttpContext context) { return this.response; } }; httpclient.execute(producer3, consumer3, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response3) { latch2.countDown(); System.out.println(request2.getRequestLine() + "->" + response3.getStatusLine()); } @Override public void failed(final Exception ex) { latch2.countDown(); System.out.println(request2.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch2.countDown(); System.out.println(request2.getRequestLine() + " cancelled"); } }); latch2.await(); } finally { httpclient.close(); } }
From source file:io.galeb.services.healthchecker.testers.ApacheHttpClientTester.java
public boolean connect() throws RuntimeException, InterruptedException, ExecutionException { if (url == null || returnType == null || expectedReturn == null) { return false; }/*from ww w.java 2s .c o m*/ final CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); try { httpclient.start(); final CountDownLatch latch = new CountDownLatch(1); final HttpGet request = new HttpGet(url); request.setHeader(HttpHeaders.HOST, host); final HttpAsyncRequestProducer producer = HttpAsyncMethods.create(request); final RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT) .setSocketTimeout(defaultTimeout).setConnectTimeout(defaultTimeout) .setConnectionRequestTimeout(defaultTimeout).build(); request.setConfig(requestConfig); final AsyncCharConsumer<HttpResponse> consumer = new AsyncCharConsumer<HttpResponse>() { HttpResponse response; @Override protected void onCharReceived(CharBuffer buf, IOControl iocontrol) throws IOException { return; } @Override protected HttpResponse buildResult(HttpContext context) throws Exception { return response; } @Override protected void onResponseReceived(HttpResponse response) throws HttpException, IOException { this.response = response; } }; httpclient.execute(producer, consumer, new FutureCallback<HttpResponse>() { @Override public void cancelled() { latch.countDown(); isOk = false; } @Override public void completed(HttpResponse response) { latch.countDown(); final int statusCode = response.getStatusLine().getStatusCode(); InputStream contentIS = null; String content = ""; try { contentIS = response.getEntity().getContent(); content = IOUtils.toString(contentIS); } catch (IllegalStateException | IOException e) { logger.ifPresent(log -> log.debug(e)); } if (returnType.startsWith("httpCode")) { returnType = returnType.replaceFirst("httpCode", ""); } // isOk = statusCode == Integer.parseInt(returnType); // Disable temporarily statusCode check isOk = true; } @Override public void failed(Exception e) { latch.countDown(); isOk = false; logger.ifPresent(log -> log.debug(e)); } }); latch.await(); } catch (final RuntimeException e) { isOk = false; logger.ifPresent(log -> log.error(e)); } finally { try { httpclient.close(); } catch (final IOException e) { logger.ifPresent(log -> log.debug(e)); } } return isOk; }
From source file:com.baidubce.http.BceHttpClient.java
/** * Executes the request and returns the result. * * @param request The BCE request to send to the remote server * @param responseClass A response handler to accept a successful response from the remote server * @param responseHandlers A response handler to accept an unsuccessful response from the remote server * * @throws com.baidubce.BceClientException If any errors are encountered on the client while making the * request or handling the response. * @throws com.baidubce.BceServiceException If any errors occurred in BCE while processing the request. *///from w w w . j av a2s. com public <T extends AbstractBceResponse> T execute(InternalRequest request, Class<T> responseClass, HttpResponseHandler[] responseHandlers) { // Apply whatever request options we know how to handle, such as user-agent. request.addHeader(Headers.USER_AGENT, this.config.getUserAgent()); BceCredentials credentials = config.getCredentials(); if (request.getCredentials() != null) { credentials = request.getCredentials(); } long delayForNextRetryInMillis = 0; for (int attempt = 1;; ++attempt) { HttpRequestBase httpRequest = null; CloseableHttpResponse httpResponse = null; CloseableHttpAsyncClient httpAsyncClient = null; try { // Sign the request if credentials were provided if (credentials != null) { this.signer.sign(request, credentials); } requestLogger.debug("Sending Request: {}", request); httpRequest = this.createHttpRequest(request); HttpContext httpContext = this.createHttpContext(request); if (this.isHttpAsyncPutEnabled && httpRequest.getMethod().equals("PUT")) { httpAsyncClient = this.createHttpAsyncClient(this.createNHttpClientConnectionManager()); httpAsyncClient.start(); Future<HttpResponse> future = httpAsyncClient.execute(HttpAsyncMethods.create(httpRequest), new BasicAsyncResponseConsumer(), httpContext, null); httpResponse = new BceCloseableHttpResponse(future.get()); } else { httpResponse = this.httpClient.execute(httpRequest, httpContext); } HttpUtils.printRequest(httpRequest); BceHttpResponse bceHttpResponse = new BceHttpResponse(httpResponse); T response = responseClass.newInstance(); for (HttpResponseHandler handler : responseHandlers) { if (handler.handle(bceHttpResponse, response)) { break; } } // everything is ok return response; } catch (Exception e) { if (logger.isInfoEnabled()) { logger.info("Unable to execute HTTP request", e); } BceClientException bce; if (e instanceof BceClientException) { bce = (BceClientException) e; } else { bce = new BceClientException("Unable to execute HTTP request", e); } delayForNextRetryInMillis = this.getDelayBeforeNextRetryInMillis(httpRequest, bce, attempt, this.config.getRetryPolicy()); if (delayForNextRetryInMillis < 0) { throw bce; } logger.debug("Retriable error detected, will retry in {} ms, attempt number: {}", delayForNextRetryInMillis, attempt); try { Thread.sleep(delayForNextRetryInMillis); } catch (InterruptedException e1) { throw new BceClientException("Delay interrupted", e1); } if (request.getContent() != null) { request.getContent().restart(); } if (httpResponse != null) { try { HttpEntity entity = httpResponse.getEntity(); if (entity != null && entity.isStreaming()) { final InputStream instream = entity.getContent(); if (instream != null) { instream.close(); } } } catch (IOException e1) { logger.debug("Fail to consume entity.", e1); try { httpResponse.close(); } catch (IOException e2) { logger.debug("Fail to close connection.", e2); } } } } finally { try { if (httpAsyncClient != null) { httpAsyncClient.close(); } } catch (IOException e) { logger.debug("Fail to close HttpAsyncClient", e); } } } }