Apache HttpAsyncClient Tutorial – Apache HttpAsyncClient教程

最后修改: 2014年 12月 1日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial we’ll illustrate the most common use cases of the Apache HttpAsyncClient – from basic usage, to how to set up a proxy, how to use SSL certificate and finally – how to authenticate with the async client.

在本教程中,我们将说明Apache HttpAsyncClient的最常见的使用情况 – 从基本用法,到如何设置代理,如何使用SSL证书,最后 – 如何用async客户端进行认证

2. Simple Example

2.简单的例子

First – let’s see how to use HttpAsyncClient in a simple example – send a GET request:

首先–让我们看看如何在一个简单的例子中使用HttpAsyncClient–发送一个GET请求。

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

Note how we need to start the async client before using it; without that, we would 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)

3. Multi-Threading With HttpAsyncClient

3.用HttpAsyncClient的多线程技术

Now – let’s see how to use HttpAsyncClient to execute multiple requests simultaneously.

现在–让我们看看如何使用HttpAsyncClient来同时执行多个请求。

In the following example – we send three GET requests to three different host using HttpAsyncClient and PoolingNHttpClientConnectionManager:

在下面的例子中,我们使用HttpAsyncClientPoolingNHttpClientConnectionManager向三个不同的主机发送三个GET请求。

@Test
public void whenUseMultipleHttpAsyncClient_thenCorrect() throws Exception {
    ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
    PoolingNHttpClientConnectionManager cm = 
      new PoolingNHttpClientConnectionManager(ioReactor);
    CloseableHttpAsyncClient client = 
      HttpAsyncClients.custom().setConnectionManager(cm).build();
    client.start();
    
    String[] toGet = { 
        "http://www.google.com/", 
        "http://www.apache.org/", 
        "http://www.bing.com/" 
    };

    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();
    }
}

Here is our GetThread implementation to handle the response:

这里是我们的GetThread实现,用于处理响应。

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());
        }
    }
}

4. Proxy With HttpAsyncClient

4.用HttpAsyncClient进行代理

Next – let’s see how to set up and use a proxy with the HttpAsyncClient.

接下来–让我们看看如何用HttpAsyncClient设置和使用一个proxy

In the following example – we send a HTTP GET request over proxy:

在下面的例子中,我们通过代理发送一个HTTP GET请求

@Test
public void whenUseProxyWithHttpClient_thenCorrect() 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("https://issues.apache.org/");
    request.setConfig(config);
    
    Future<HttpResponse> future = client.execute(request, null);
    HttpResponse response = future.get();
    
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}

5. SSL Certificate With HttpAsyncClient

5.使用HttpAsyncClient的SSL证书

Now – let’s see how to use a SSL Certificate with HttpAsyncClient.

现在–让我们看看如何使用SSL证书HttpAsyncClient

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

在下面的例子中,我们将HttpAsyncClient配置为接受所有证书

@Test
public void whenUseSSLWithHttpAsyncClient_thenCorrect() 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("https://mms.nw.ru/");
    Future<HttpResponse> future = client.execute(request, null);
    HttpResponse response = future.get();
    
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}

6. Cookies With HttpAsyncClient

6.使用HttpAsyncClient的Cookies

Next – let’s see how to use cookies with HttpAsyncClient.

接下来–让我们看看如何用HttpAsyncClient来使用cookies。

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

在下面的例子中–我们在发送请求前设置一个cookie值

@Test
public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
    cookie.setDomain(".github.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    
    CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
    client.start();
    
    HttpGet request = new HttpGet("http://www.github.com");
    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();
}

7. Authentication With HttpAsyncClient

7.用HttpAsyncClient进行身份验证

Next – let’s see how to use authentication with HttpAsyncClient.

接下来–让我们看看如何用HttpAsyncClient来使用认证。

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

在下面的例子中–我们使用CredentialsProvider来通过基本认证访问一个主机。

@Test
public void whenUseAuthenticationWithHttpAsyncClient_thenCorrect() 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();
}

8. Conclusion

8.结论

In this article, we illustrated the various use cases of the asynchronous Apache Http client.

在这篇文章中,我们说明了异步Apache Http客户端的各种使用情况。

The implementation of all these examples and code snippets can be found in my github project – this is an Eclipse based project, so it should be easy to import and run as it is.

所有这些例子和代码片段的实现可以在我的github项目中找到 – 这是一个基于Eclipse的项目,所以它应该很容易导入和运行。