HttpClient高級(jí)進(jìn)階-HttpAsyncClient

簡(jiǎn)述

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

簡(jiǎn)單Demo

首先技健,讓我們看一下如何在一個(gè)簡(jiǎn)單的例子中使用HttpAsyncClient骄呼,發(fā)送一個(gè)GET請(qǐng)求:

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

注意我們?cè)谑褂弥靶枰獑?dòng)HttpAsyncClients ; 沒(méi)有它,我們會(huì)得到以下異常:

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進(jìn)行多線程處理

現(xiàn)在琼富,讓我們看看如何使用HttpAsyncClient同時(shí)執(zhí)行多個(gè)請(qǐng)求仪吧。

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

@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實(shí)現(xiàn)來(lái)處理響應(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的代理

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

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

@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證書(shū)

現(xiàn)在械蹋,讓我們來(lái)看看如何使用SSL證書(shū)與HttpAsyncClient出皇。

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

@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

接下來(lái)朝蜘,讓我們看看如何在HttpAsyncClient中使用cookie 。

在以下示例中涩金,我們?cè)诎l(fā)送請(qǐng)求之前設(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進(jìn)行身份驗(yàn)證

接下來(lái)谱醇,讓我們看看如何使用HttpAsyncClient進(jìn)行身份驗(yàn)證暇仲。

在以下示例中,我們使用CredentialsProvider通過(guò)基本身份驗(yàn)證訪問(wèn)主機(jī):

@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)容希望你對(duì)HttpAsyncClient有深刻的了解

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末副渴,一起剝皮案震驚了整個(gè)濱河市奈附,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌煮剧,老刑警劉巖斥滤,帶你破解...
    沈念sama閱讀 218,122評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異勉盅,居然都是意外死亡佑颇,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門草娜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)挑胸,“玉大人,你說(shuō)我怎么就攤上這事宰闰〔绻螅” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,491評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵移袍,是天一觀的道長(zhǎng)解藻。 經(jīng)常有香客問(wèn)我,道長(zhǎng)葡盗,這世上最難降的妖魔是什么螟左? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,636評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮戳粒,結(jié)果婚禮上路狮,老公的妹妹穿的比我還像新娘。我一直安慰自己蔚约,他們只是感情好奄妨,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著苹祟,像睡著了一般砸抛。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上树枫,一...
    開(kāi)封第一講書(shū)人閱讀 51,541評(píng)論 1 305
  • 那天直焙,我揣著相機(jī)與錄音,去河邊找鬼砂轻。 笑死奔誓,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的搔涝。 我是一名探鬼主播厨喂,決...
    沈念sama閱讀 40,292評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼和措,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了蜕煌?” 一聲冷哼從身側(cè)響起派阱,我...
    開(kāi)封第一講書(shū)人閱讀 39,211評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎斜纪,沒(méi)想到半個(gè)月后贫母,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,655評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡盒刚,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評(píng)論 3 336
  • 正文 我和宋清朗相戀三年腺劣,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片伪冰。...
    茶點(diǎn)故事閱讀 39,965評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡誓酒,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出贮聂,到底是詐尸還是另有隱情靠柑,我是刑警寧澤,帶...
    沈念sama閱讀 35,684評(píng)論 5 347
  • 正文 年R本政府宣布吓懈,位于F島的核電站歼冰,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏耻警。R本人自食惡果不足惜隔嫡,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評(píng)論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望甘穿。 院中可真熱鬧腮恩,春花似錦、人聲如沸温兼。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,894評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)募判。三九已至荡含,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間届垫,已是汗流浹背释液。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,012評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留装处,地道東北人误债。 一個(gè)月前我還...
    沈念sama閱讀 48,126評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親寝蹈。 傳聞我的和親對(duì)象是個(gè)殘疾皇子糟袁,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容