HttpClient高級進階-HttpAsyncClient

簡述

本文介紹Apache HttpAsyncClient的最常見用例,從基本用法到如何設(shè)置代理,如何使用SSL證書以及最后如何使用異步客戶端進行身份驗證。

簡單Demo

首先,讓我們看一下如何在一個簡單的例子中使用HttpAsyncClient,發(fā)送一個GET請求:

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

注意我們在使用之前需要啟動HttpAsyncClients ; 沒有它,我們會得到以下異常:

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)

使用HttpAsyncClient進行多線程處理

現(xiàn)在,讓我們看看如何使用HttpAsyncClient同時執(zhí)行多個請求。

在以下示例中,我們使用HttpAsyncClient和PoolingNHttpClientConnectionManager向三個不同的主機發(fā)送三個GET請求:

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

以下是我們的GetThread實現(xiàn)來處理響應(yīng):

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

使用HttpAsyncClient的代理

接下來,讓我們來看看如何設(shè)置和使用代理服務(wù)器與HttpAsyncClient。

在以下示例中,我們通過代理發(fā)送HTTP GET請求:

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

使用HttpAsyncClient的SSL證書

現(xiàn)在,讓我們來看看如何使用SSL證書與HttpAsyncClient。

在以下示例中, 我們將HttpAsyncClient配置為接受所有證書:

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


使用HttpAsyncClient的Cookie

接下來,讓我們看看如何在HttpAsyncClient中使用cookie 。

在以下示例中,我們在發(fā)送請求之前設(shè)置cookie值:

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

使用HttpAsyncClient進行身份驗證

接下來,讓我們看看如何使用HttpAsyncClient進行身份驗證。

在以下示例中,我們使用CredentialsProvider通過基本身份驗證訪問主機:

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

結(jié)論

本文介紹的內(nèi)容希望你對HttpAsyncClient有深刻的了解

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容