The paper

This article covers the most common use cases of Apache HttpAsyncClient, from basic usage to how to set up proxies, how to use SSL certificates, and finally how to use asynchronous clients for authentication.

A simple Demo

First, let’s look at how to use HttpAsyncClient in a simple example to send a GET request:

@Test
public void test() throws Exception {
    CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();
    HttpGet request = new HttpGet("http://localhost:8080");
     
    Future<HttpResponse> future = client.execute(request, null);
    HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
Copy the code

Note that we need to launch HttpAsyncClients before using it; Without it, we get the following exception:

java.lang.IllegalStateException: Request cannot be executed; I/O reactor status: INACTIVE
    at o.a.h.u.Asserts.check(Asserts.java:46)
    at o.a.h.i.n.c.CloseableHttpAsyncClientBase.
      ensureRunning(CloseableHttpAsyncClientBase.java:90)
Copy the code

Use HttpAsyncClient for multi-threading

Now, let’s look at how to execute multiple requests simultaneously using HttpAsyncClient.

In the example below, we use HttpAsyncClient and PoolingNHttpClientConnectionManager to three different host sends a GET request:

@Test
public void test() throws Exception {
    ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
    PoolingNHttpClientConnectionManager cm = 
      new PoolingNHttpClientConnectionManager(ioReactor);
    CloseableHttpAsyncClient client = 
      HttpAsyncClients.custom().setConnectionManager(cm).build();
    client.start();
     
    String[] toGet = {
            "192.168.0.101:8080"."192.168.0.102:8080"."192.168.0.103:8080"
    };
 
    GetThread[] threads = new GetThread[toGet.length];
    for (int i = 0; i < threads.length; i++) {
        HttpGet request = new HttpGet(toGet[i]);
        threads[i] = new GetThread(client, request);
    }
 
    for (GetThread thread : threads) {
        thread.start();
    }
    for(GetThread thread : threads) { thread.join(); }}Copy the code

Here is our GetThread implementation to handle the response:

static class GetThread extends Thread {
    private CloseableHttpAsyncClient client;
    private HttpContext context;
    private HttpGet request;
 
    public GetThread(CloseableHttpAsyncClient client,HttpGet req){
        this.client = client;
        context = HttpClientContext.create();
        this.request = req;
    }
 
    @Override
    public void run() { try { Future<HttpResponse> future = client.execute(request, context, null); HttpResponse response = future.get(); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } catch (Exception ex) { System.out.println(ex.getLocalizedMessage()); }}}Copy the code

Proxy using HttpAsyncClient

Next, let’s look at how to set up and use a proxy server with HttpAsyncClient.

In the following example, we send an HTTP GET request through a proxy:

@Test
public void test() throws Exception {
    CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();
     
    HttpHost proxy = new HttpHost("74.50.126.248", 3127);
    RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
    HttpGet request = new HttpGet("http://192.168.0.101");
    request.setConfig(config);
     
    Future<HttpResponse> future = client.execute(request, null);
    HttpResponse response = future.get();
     
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
Copy the code

Use HttpAsyncClient’s SSL certificate

Now let’s look at how to use SSL certificates with HttpAsyncClient.

In the following example, we configure HttpAsyncClient to accept all certificates:

@Test
public void test() throws Exception {
    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] certificate,  String authType) {
            return true; }}; SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy).build(); CloseableHttpAsyncClient client = HttpAsyncClients.custom() .setSSLHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) .setSSLContext(sslContext).build(); client.start(); HttpGet request = new HttpGet("");
    Future<HttpResponse> future = client.execute(request, null);
    HttpResponse response = future.get();
     
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}


Copy the code

Use HttpAsyncClient’s Cookie

Next, let’s look at how to use cookies in HttpAsyncClient.

In the following example, we set the cookie value before sending the request:

@Test
public void test() throws Exception {
    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie cookie = new BasicClientCookie("JSESSIONID"."1234");
    cookie.setDomain(".william.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
     
    CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
    client.start();
     
    HttpGet request = new HttpGet("http://localhost:8080");
    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    Future<HttpResponse> future = client.execute(request, localContext, null);
    HttpResponse response = future.get();
     
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
Copy the code

Use HttpAsyncClient for authentication

Next, let’s look at how to use HttpAsyncClient for authentication.

In the following example, we use CredentialsProvider to access the host through basic authentication:

@Test
public void test() throws Exception {
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("user"."pass");
    provider.setCredentials(AuthScope.ANY, creds);
     
    CloseableHttpAsyncClient client = 
      HttpAsyncClients.custom().setDefaultCredentialsProvider(provider).build();
    client.start();
     
    HttpGet request = new HttpGet("http://localhost:8080");
    Future<HttpResponse> future = client.execute(request, null);
    HttpResponse response = future.get();
     
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
Copy the code

conclusion

Hopefully, this article introduces you to HttpAsyncClient