HttpAsyncClientチュートリアル

HttpAsyncClientチュートリアル

1. 概要

このチュートリアルでは、ApacheHttpAsyncClientの最も一般的な使用例を説明します–基本的な使用法から、set up a proxyの使用方法、SSL certificateの使用方法、そして最後に–%(t3 )非同期クライアントを使用します。 __

2. 簡単な例

まず、簡単な例でHttpAsyncClientを使用する方法を見てみましょう–GETリクエストを送信します。

@Test
public void whenUseHttpAsyncClient_thenCorrect() throws Exception {
    CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();
    HttpGet request = new HttpGet("http://www.google.com");

    Future future = client.execute(request, null);
    HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}

we need to start the async client before using it;に注意してください。それがないと、次の例外が発生します。

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. HttpAsyncClientを使用したマルチスレッド

では、HttpAsyncClientを使用して複数のリクエストを同時に実行する方法を見てみましょう。

次の例では、HttpAsyncClientPoolingNHttpClientConnectionManagerを使用して3つのGETリクエストを3つの異なるホストに送信します。

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

応答を処理するための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 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. HttpAsyncClientを使用したプロキシ

次へ–HttpAsyncClientproxyを設定して使用する方法を見てみましょう。

次の例では、HTTPGET request over proxyを送信します。

@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 future = client.execute(request, null);
    HttpResponse response = future.get();

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}

5. HttpAsyncClientのSSL証明書

では、SSL CertificateHttpAsyncClientとともに使用する方法を見てみましょう。

次の例では、HttpAsyncClientaccept all certificatesに構成します。

@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 future = client.execute(request, null);
    HttpResponse response = future.get();

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}

6. HttpAsyncClientのCookie

次へ–HttpAsyncClientでCookieを使用する方法を見てみましょう。

次の例では、set a cookie value before sending the request

@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 future = client.execute(request, localContext, null);
    HttpResponse response = future.get();

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}

7. HttpAsyncClientによる認証

次へ–HttpAsyncClientで認証を使用する方法を見てみましょう。

次の例では、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 future = client.execute(request, null);
    HttpResponse response = future.get();

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}

8. 結論

この記事では、非同期Apache Httpクライアントのさまざまな使用例を示しました。

これらすべての例とコードスニペットcan be found in my github projectの実装–これはEclipseベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。