Java Code Examples for org.apache.http.impl.nio.client.CloseableHttpAsyncClient#start()

The following examples show how to use org.apache.http.impl.nio.client.CloseableHttpAsyncClient#start() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApacheHttpAsyncClientPluginIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
    httpClient.start();
    HttpHost httpHost = new HttpHost("localhost", getPort());
    HttpGet httpGet = new HttpGet("/hello2");
    SimpleFutureCallback callback = new SimpleFutureCallback();
    Future<HttpResponse> future = httpClient.execute(httpHost, httpGet, callback);
    callback.latch.await();
    httpClient.close();
    int responseStatusCode = future.get().getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
}
 
Example 2
Source File: AsyncNetwork.java    From jlitespider with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void begin() throws InterruptedException {
	CloseableHttpAsyncClient httpclient = httpAsyncClientBuilder.build();
	httpclient.start();
	new Thread(() -> {
		while (true) {
			try {
				Url url = this.urlQueue.take();
				httpclient.execute(HttpAsyncMethods.createGet(url.url), new MyResponseConsumer(url), new MyFutureCallback(url));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}).start();

}
 
Example 3
Source File: ODataProductSynchronizer.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public CloseableHttpAsyncClient generateClient ()
{
   CredentialsProvider credsProvider = new BasicCredentialsProvider();
   credsProvider.setCredentials(new AuthScope (AuthScope.ANY),
           new UsernamePasswordCredentials(serviceUser, servicePass));
   RequestConfig rqconf = RequestConfig.custom()
         .setCookieSpec(CookieSpecs.DEFAULT)
         .setSocketTimeout(Timeouts.SOCKET_TIMEOUT)
         .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT)
         .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT)
         .build();
   CloseableHttpAsyncClient res = HttpAsyncClients.custom ()
         .setDefaultCredentialsProvider (credsProvider)
         .setDefaultRequestConfig(rqconf)
         .build ();
   res.start ();
   return res;
}
 
Example 4
Source File: HttpClientManager.java    From azure-notificationhubs-java-backend with Apache License 2.0 6 votes vote down vote up
private static void initializeHttpAsyncClient() {
    synchronized (HttpClientManager.class) {
        if (httpAsyncClient == null) {
            RequestConfig config = RequestConfig.custom()
                    .setConnectionRequestTimeout(connectionRequestTimeout)
                    .setConnectTimeout(connectionTimeout)
                    .setSocketTimeout(socketTimeout)
                    .build();
            CloseableHttpAsyncClient client = HttpAsyncClientBuilder.create()
                    .setDefaultRequestConfig(config)
                    .build();
            client.start();
            httpAsyncClient = client;
        }
    }
}
 
Example 5
Source File: MicrometerHttpClientInterceptorTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void uriIsReadFromHttpHeader(@WiremockResolver.Wiremock WireMockServer server) throws Exception {
    server.stubFor(any(anyUrl()));
    MicrometerHttpClientInterceptor interceptor = new MicrometerHttpClientInterceptor(registry, Tags.empty(), true);
    CloseableHttpAsyncClient client = asyncClient(interceptor);
    client.start();
    HttpGet request = new HttpGet(server.baseUrl());
    request.addHeader(DefaultUriMapper.URI_PATTERN_HEADER, "/some/pattern");

    Future<HttpResponse> future = client.execute(request, null);
    HttpResponse response = future.get();

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
    assertThat(registry.get("httpcomponents.httpclient.request").tag("uri", "/some/pattern").tag("status", "200").timer().count())
            .isEqualTo(1);

    client.close();
}
 
Example 6
Source File: EtcdClient.java    From jetcd with Apache License 2.0 5 votes vote down vote up
static CloseableHttpAsyncClient buildDefaultHttpClient() {
    // TODO: Increase timeout??
    RequestConfig requestConfig = RequestConfig.custom().build();
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig).build();
    httpClient.start();
    return httpClient;
}
 
Example 7
Source File: MicrometerHttpClientInterceptorTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void asyncRequest(@WiremockResolver.Wiremock WireMockServer server) throws Exception {
    server.stubFor(any(anyUrl()));
    CloseableHttpAsyncClient client = asyncClient();
    client.start();
    HttpGet request = new HttpGet(server.baseUrl());

    Future<HttpResponse> future = client.execute(request, null);
    HttpResponse response = future.get();

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
    assertThat(registry.get("httpcomponents.httpclient.request").timer().count()).isEqualTo(1);

    client.close();
}
 
Example 8
Source File: HttpAsyncClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenUseSSLWithHttpAsyncClient_thenCorrect() throws Exception {
    final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
    final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();

    final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext).build();

    client.start();
    final HttpGet request = new HttpGet(HOST_WITH_SSL);
    final Future<HttpResponse> future = client.execute(request, null);
    final HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
 
Example 9
Source File: ImportRunner.java    From newts with Apache License 2.0 5 votes vote down vote up
private Observable<Boolean> restPoster(Observable<List<Sample>> samples,  MetricRegistry metrics) {

        final CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        httpClient.start();


        return samples

                // turn each batch into json
                .map(toJSON())

                // meter them as the go into the post code
                .map(meter(metrics.meter("posts"), String.class))

                // post the json to the REST server
                .mergeMap(postJSON(m_restUrl, httpClient))

                // meter the responses
                .map(meter(metrics.meter("responses"), ObservableHttpResponse.class))
                
                // count sample completions
                .map(meter(metrics.meter("samples-completed"), m_samplesPerBatch, ObservableHttpResponse.class))

                // make sure every request has a successful return code
                .all(successful())
                
                .doOnCompleted(new Action0() {

                    @Override
                    public void call() {
                        try {
                            httpClient.close();
                        } catch (IOException e) {
                            System.err.println("Failed to close httpClient!");
                            e.printStackTrace();
                        }
                    }
                    
                });
    }
 
Example 10
Source File: TestUtils.java    From salt-netapi-client with MIT License 5 votes vote down vote up
public static CloseableHttpAsyncClient defaultClient() {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(0)
            .setConnectTimeout(0)
            .setSocketTimeout(0)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    CloseableHttpAsyncClient asyncHttpClient = httpClientBuilder.build();
    asyncHttpClient.start();
    return asyncHttpClient;
}
 
Example 11
Source File: AsyncClientHttpExchangeFutureCallback.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig).build();
    try {
        httpclient.start();
        final HttpGet[] requests = new HttpGet[] { new HttpGet("http://www.apache.org/"),
                new HttpGet("https://www.verisign.com/"), new HttpGet("http://www.google.com/") };
        final CountDownLatch latch = new CountDownLatch(requests.length);
        for (final HttpGet request : requests) {
            httpclient.execute(request, new FutureCallback<HttpResponse>() {

                @Override
                public void completed(final HttpResponse response) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
                }

                @Override
                public void failed(final Exception ex) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + ex);
                }

                @Override
                public void cancelled() {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + " cancelled");
                }

            });
        }
        latch.await();
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
 
Example 12
Source File: AsyncClientHttpExchange.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {
        httpclient.start();
        HttpGet request = new HttpGet("http://www.apache.org/");
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
 
Example 13
Source File: HttpClientUtils.java    From salt-netapi-client with MIT License 5 votes vote down vote up
/**
 * Creates a simple default http client
 * @return HttpAsyncClient
 */
public static CloseableHttpAsyncClient defaultClient() {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(0)
            .setConnectTimeout(10000)
            .setSocketTimeout(20000)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    CloseableHttpAsyncClient asyncHttpClient = httpClientBuilder.build();
    asyncHttpClient.start();
    return asyncHttpClient;
}
 
Example 14
Source File: HttpAsyncClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
    final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();
    final HttpGet request = new HttpGet(HOST);

    final Future<HttpResponse> future = client.execute(request, null);
    final HttpResponse response = future.get();

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
 
Example 15
Source File: ClosableAsyncHttpClientIT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
 public void test() throws Exception {
     CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom().useSystemProperties().build();
     httpClient.start();
     
     try {
         HttpPost httpRequest = new HttpPost(webServer.getCallHttpUrl());
         
         List<NameValuePair> params = new ArrayList<NameValuePair>();
         params.add(new BasicNameValuePair("param1", "value1"));
         httpRequest.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8.name()));
         
         Future<HttpResponse> responseFuture = httpClient.execute(httpRequest, null);
         HttpResponse response = (HttpResponse) responseFuture.get();
         
         if ((response != null) && (response.getEntity() != null)) {
             EntityUtils.consume(response.getEntity());
         }
     } finally {
         httpClient.close();
     }
     
     PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
     verifier.printCache();
     
     verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", CloseableHttpAsyncClient.class.getMethod("execute", HttpUriRequest.class, FutureCallback.class)));
     final String destinationId = webServer.getHostAndPort();
     final String httpUrl = webServer.getCallHttpUrl();
     verifier.verifyTrace(async(
                 event("HTTP_CLIENT_4", Class.forName("org.apache.http.impl.nio.client.DefaultClientExchangeHandlerImpl").getMethod("start"), null, null, destinationId,
                         annotation("http.url", httpUrl), annotation("http.entity", "param1=value1")),
                 event("ASYNC","Asynchronous Invocation"),
                 event("HTTP_CLIENT_4_INTERNAL", BasicFuture.class.getMethod("completed", Object.class))
     ));
     verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", BasicFuture.class.getMethod("get")));
     
     verifier.verifyTraceCount(0);
}
 
Example 16
Source File: HttpComponentsAsyncClientHttpRequestFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private HttpAsyncClient startAsyncClient() {
	HttpAsyncClient client = getAsyncClient();
	if (client instanceof CloseableHttpAsyncClient) {
		CloseableHttpAsyncClient closeableAsyncClient = (CloseableHttpAsyncClient) client;
		if (!closeableAsyncClient.isRunning()) {
			closeableAsyncClient.start();
		}
	}
	return client;
}
 
Example 17
Source File: ApacheHttpAsyncClientBenchmarks.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override protected CloseableHttpAsyncClient newClient(HttpTracing httpTracing) {
  CloseableHttpAsyncClient result = TracingHttpAsyncClientBuilder.create(httpTracing).build();
  result.start();
  return result;
}
 
Example 18
Source File: ApacheHttpAsyncClientBenchmarks.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override protected CloseableHttpAsyncClient newClient() {
  CloseableHttpAsyncClient result = HttpAsyncClients.custom().build();
  result.start();
  return result;
}
 
Example 19
Source File: AsyncHttpClientTest.java    From cetty with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
        HttpClientGenerator<CloseableHttpAsyncClient> asyncHttpClientGenerator = new AsyncHttpClientGenerator();
        Payload payload = new Payload();
        CloseableHttpAsyncClient client = asyncHttpClientGenerator.getClient(payload);

        client.start();

        final HttpGet[] requests = new HttpGet[]{
                new HttpGet("http://www.apache.org/"),
                new HttpGet("http://www.baidu.com/"),
                new HttpGet("http://www.oschina.net/")
        };

        for(final HttpGet request: requests){
            client.execute(request, new FutureCallback(){
                @Override
                public void completed(Object obj) {
                    final HttpResponse response = (HttpResponse)obj;
                    System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
                }

                @Override
                public void failed(Exception excptn) {
                    System.out.println(request.getRequestLine() + "->" + excptn);
                }

                @Override
                public void cancelled() {
                    System.out.println(request.getRequestLine() + "cancelled");
                }
            });
        }


//        for (int i = 0; i < 2; i++) {
//            HttpRequestBase httpGet = new HttpGet("http://www.baidu.com");
//            client.execute(httpGet, new Back());
//            System.out.println("index :" + i);
//            httpGet.releaseConnection();
//        }

//        client.execute(httpGet, new Back());
    }
 
Example 20
Source File: PushService.java    From webpush-java with MIT License 3 votes vote down vote up
/**
 * Send a notification, but don't wait for the response.
 *
 * @param notification
 * @param encoding
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
 * @throws JoseException
 */
public Future<HttpResponse> sendAsync(Notification notification, Encoding encoding) throws GeneralSecurityException, IOException, JoseException {
    HttpPost httpPost = preparePost(notification, encoding);

    final CloseableHttpAsyncClient closeableHttpAsyncClient = HttpAsyncClients.createSystem();
    closeableHttpAsyncClient.start();

    return closeableHttpAsyncClient.execute(httpPost, new ClosableCallback(closeableHttpAsyncClient));
}