HttpAsyncClient-Lernprogramm

HttpAsyncClient Tutorial

1. Überblick

In diesem Tutorial werden die häufigsten Anwendungsfälle des ApacheHttpAsyncClient veranschaulicht - von der Grundverwendung überset up a proxy bis hin zur Verwendung vonSSL certificate und schließlichauthenticate) s mit dem asynchronen Client. __

2. Einfaches Beispiel

Senden Sie zunächst eine GET-Anfrage, um zu sehen, wieHttpAsyncClient in einem einfachen Beispiel verwendet werden:

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

Beachten Sie, wiewe need to start the async client before using it; ohne das würden wir die folgende Ausnahme bekommen:

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. Multithreading mitHttpAsyncClient

Nun wollen wir sehen, wie Sie mitHttpAsyncClient mehrere Anforderungen gleichzeitig ausführen.

Im folgenden Beispiel senden wir drei GET-Anforderungen mitHttpAsyncClient undPoolingNHttpClientConnectionManager an drei verschiedene Hosts:

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

Hier ist die Implementierung vonGetThread, um die Antwort zu verarbeiten:

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. Proxy mitHttpAsyncClient

Weiter - sehen wir uns an, wie Sieproxy mitHttpAsyncClient einrichten und verwenden.

Im folgenden Beispiel senden wir ein 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-Zertifikat mitHttpAsyncClient

Nun wollen wir sehen, wie manSSL Certificate mitHttpAsyncClient verwendet.

Im folgenden Beispiel konfigurieren wirHttpAsyncClient bisaccept 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. Cookies mitHttpAsyncClient

Weiter - sehen wir uns an, wie Cookies mitHttpAsyncClient verwendet werden.

Im folgenden Beispiel - wirset 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. Authentifizierung mit HttpAsyncClient

Weiter - sehen wir uns an, wie die Authentifizierung mitHttpAsyncClient verwendet wird.

Im folgenden Beispiel verwenden wirCredentialsProvider, um über die Basisauthentifizierung auf einen Host zuzugreifen:

@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. Fazit

In diesem Artikel haben wir die verschiedenen Anwendungsfälle des asynchronen Apache Http-Clients veranschaulicht.

Die Implementierung all dieser Beispiele und Codefragmentecan be found in my github project - dies ist ein Eclipse-basiertes Projekt, daher sollte es einfach zu importieren und auszuführen sein, wie es ist.