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

The following examples show how to use org.apache.http.impl.nio.client.CloseableHttpAsyncClient#close() . 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: HttpAsyncClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, "1234");
    cookie.setDomain(COOKIE_DOMAIN);
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
    client.start();
    final HttpGet request = new HttpGet(HOST_WITH_COOKIE);

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    final Future<HttpResponse> future = client.execute(request, localContext, null);
    final HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
 
Example 2
Source File: Async.java    From salt-netapi-client with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    CloseableHttpAsyncClient httpClient = HttpClientUtils.defaultClient();
    // Init the client
    SaltClient client = new SaltClient(URI.create(SALT_API_URL), new HttpAsyncClientImpl(httpClient));

    // Clean up afterwards by calling close()
    Runnable cleanup = () -> {
        try {
            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    };

    // Perform a non-blocking login
    client.login(USER, PASSWORD, AuthModule.AUTO)
            .thenAccept(t -> System.out.println("Token -> " + t.getToken()))
            .thenRun(cleanup);
}
 
Example 3
Source File: AsyncClientExecuteProxy.java    From yunpian-java-sdk with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {
        httpclient.start();
        HttpHost proxy = new HttpHost("someproxy", 8080);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet request = new HttpGet("https://issues.apache.org/");
        request.setConfig(config);
        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();
    }
}
 
Example 4
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());
    HttpPost httpPost = new HttpPost("/hello4");
    SimpleFutureCallback callback = new SimpleFutureCallback();
    Future<HttpResponse> future = httpClient.execute(httpHost, httpPost, callback);
    callback.latch.await();
    httpClient.close();
    int responseStatusCode = future.get().getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
}
 
Example 5
Source File: AsyncClientHttpExchangeStreaming.java    From yunpian-java-sdk with MIT License 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {
        httpclient.start();
        Future<Boolean> future = httpclient.execute(HttpAsyncMethods.createGet("http://localhost:8080/"),
                new MyResponseConsumer(), null);
        Boolean result = future.get();
        if (result != null && result.booleanValue()) {
            System.out.println("Request successfully executed");
        } else {
            System.out.println("Request failed");
        }
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
 
Example 6
Source File: AsyncClientAuthentication.java    From yunpian-java-sdk with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", 443),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build();
    try {
        HttpGet httpget = new HttpGet("http://localhost/");

        System.out.println("Executing request " + httpget.getRequestLine());
        Future<HttpResponse> future = httpclient.execute(httpget, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
}
 
Example 7
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 8
Source File: AsyncClientProxyAuthentication.java    From yunpian-java-sdk with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("someproxy", 8080),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build();
    try {
        httpclient.start();
        HttpHost proxy = new HttpHost("someproxy", 8080);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet httpget = new HttpGet("https://issues.apache.org/");
        httpget.setConfig(config);
        Future<HttpResponse> future = httpclient.execute(httpget, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
}
 
Example 9
Source File: AsyncHTTPConduitFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static void shutdown(CloseableHttpAsyncClient client) {
    try {
        client.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}
 
Example 10
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 11
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 12
Source File: ApacheHttpAsyncClientPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
    httpClient.start();
    HttpPost httpPost = new HttpPost("http://localhost:" + getPort() + "/hello3");
    SimpleFutureCallback callback = new SimpleFutureCallback();
    Future<HttpResponse> future = httpClient.execute(httpPost, callback);
    callback.latch.await();
    httpClient.close();
    int responseStatusCode = future.get().getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
}
 
Example 13
Source File: ApacheHttpAsyncClientPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
    httpClient.start();
    HttpGet httpGet = new HttpGet("http://localhost:" + getPort() + "/hello1");
    SimpleFutureCallback callback = new SimpleFutureCallback();
    Future<HttpResponse> future = httpClient.execute(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 14
Source File: WebClientTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void shouldAttachTraceIdWhenCallingAnotherServiceForAsyncHttpClient()
		throws Exception {
	Span span = this.tracer.nextSpan().name("foo").start();

	CloseableHttpAsyncClient client = this.httpAsyncClientBuilder.build();
	try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span)) {
		client.start();
		Future<HttpResponse> future = client.execute(
				new HttpGet("http://localhost:" + this.port),
				new FutureCallback<HttpResponse>() {
					@Override
					public void completed(HttpResponse result) {

					}

					@Override
					public void failed(Exception ex) {

					}

					@Override
					public void cancelled() {

					}
				});
		then(future.get()).isNotNull();
	}
	finally {
		client.close();
	}

	then(this.tracer.currentSpan()).isNull();
	then(this.spans).isNotEmpty().extracting("traceId", String.class)
			.containsOnly(span.context().traceIdString());
	then(this.spans).extracting("kind.name").contains("CLIENT");
}
 
Example 15
Source File: HttpClientUtil.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
static void close(CloseableHttpAsyncClient client) {
	try {
		Log.debug("Closing HTTP client", "client", client);
		client.close();
	} catch (IOException e) {
		throw U.rte(e);
	}
}
 
Example 16
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 17
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 18
Source File: HttpAsyncClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() throws Exception {
    final CredentialsProvider provider = new BasicCredentialsProvider();
    final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
    provider.setCredentials(AuthScope.ANY, creds);
    final CloseableHttpAsyncClient client = HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build();

    final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
    client.start();
    final Future<HttpResponse> future = client.execute(request, null);
    final HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
 
Example 19
Source File: AsyncClientCustomContext.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public final static void main(String[] args) throws Exception {
	CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
	try {
		// Create a local instance of cookie store
		CookieStore cookieStore = new BasicCookieStore();

		// Create local HTTP context
		HttpClientContext localContext = HttpClientContext.create();
		// Bind custom cookie store to the local context
		localContext.setCookieStore(cookieStore);

           HttpGet httpget = new HttpGet("http://localhost/");
		System.out.println("Executing request " + httpget.getRequestLine());

		httpclient.start();

		// Pass local context as a parameter
		Future<HttpResponse> future = httpclient.execute(httpget, localContext, null);

		// Please note that it may be unsafe to access HttpContext instance
		// while the request is still being executed

		HttpResponse response = future.get();
		System.out.println("Response: " + response.getStatusLine());
		List<Cookie> cookies = cookieStore.getCookies();
		for (int i = 0; i < cookies.size(); i++) {
			System.out.println("Local cookie: " + cookies.get(i));
		}
		System.out.println("Shutting down");
	} finally {
		httpclient.close();
	}
}
 
Example 20
Source File: ApacheHttpAsyncClientBenchmarks.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override protected void close(CloseableHttpAsyncClient client) throws IOException {
  client.close();
}