Учебник HttpAsyncClient

Учебник по HttpAsyncClient

1. обзор

В этом руководстве мы проиллюстрируем наиболее распространенные варианты использования ApacheHttpAsyncClient - от базового использования до того, как использоватьset up a proxy, как использоватьSSL certificate и, наконец, - как использоватьauthenticate) s с помощью асинхронного клиента. __

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 для одновременного выполнения нескольких запросов.

В следующем примере мы отправляем три запроса GET на три разных хоста, используяHttpAsyncClient иPoolingNHttpClientConnectionManager:

@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

Далее - давайте посмотрим, как настроить и использоватьproxy сHttpAsyncClient.

В следующем примере мы отправляем 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. SSL-сертификат сHttpAsyncClient

А теперь давайте посмотрим, как использоватьSSL Certificate сHttpAsyncClient.

В следующем примере мы настраиваемHttpAsyncClient наaccept 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. Файлы cookie сHttpAsyncClient

Далее - давайте посмотрим, как использовать файлы cookie сHttpAsyncClient.

В следующем примере - weset 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, поэтому его должно быть легко импортировать и запускать как есть.