httpclient4.5基本使用

使用示例

maven依賴:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>

執(zhí)行連接請(qǐng)求示例:

        // httpclient客戶端,類似于一個(gè)瀏覽器,可以由這個(gè)客戶端執(zhí)行http請(qǐng)求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 請(qǐng)求
        HttpGet httpGet = new HttpGet("http://www.itdecent.cn/");
        // 響應(yīng)
        CloseableHttpResponse response = null;
        try {
            // execute()執(zhí)行成功會(huì)返回HttpResponse響應(yīng)
            response = httpClient.execute(httpGet);
            // 響應(yīng)體
            HttpEntity responseEntity = response.getEntity();
            System.out.println("響應(yīng)狀態(tài):" + response.getStatusLine());
            // gzip,deflate,compress
            System.out.println("響應(yīng)體編碼方式:" + responseEntity.getContentEncoding());
            // 響應(yīng)類型如text/html charset也有可能在ContentType中
            System.out.println("響應(yīng)體類型:" + responseEntity.getContentType());
            /**
             *  EntityUtils.toString()方法會(huì)將響應(yīng)體的輸入流關(guān)閉,相當(dāng)于消耗了響應(yīng)體,
             *  此時(shí)連接會(huì)回到httpclient中的連接管理器的連接池中,如果下次訪問(wèn)的路由
             *  是一樣的(如第一次訪問(wèn)http://www.itdecent.cn/,第二次訪問(wèn)
             *  http://www.itdecent.cn/search?q=java&page=1&type=note),
             *  則此連接可以被復(fù)用。
             */

            System.out.println("響應(yīng)體內(nèi)容:" + EntityUtils.toString(responseEntity));
            // 如果關(guān)閉了httpEntity的inputStream,httpEntity長(zhǎng)度應(yīng)該為0,而且再次請(qǐng)求相同路由的連接可以共用一個(gè)連接。
            // 可以通過(guò)設(shè)置連接管理器最大連接為1來(lái)驗(yàn)證。 
            response = httpClient.execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    // 關(guān)閉連接,則此次連接被丟棄
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

創(chuàng)建默認(rèn)的CloseableHttpClient實(shí)例中有一個(gè)連接管理器,最大連接數(shù)為20,每個(gè)路由最大連接數(shù)為2。因?yàn)橛辛诉B接管理器對(duì)連接的管理,我們可以放心的使用多線程來(lái)執(zhí)行請(qǐng)求,可以有多個(gè)HttpClient(我覺(jué)得沒(méi)有很大必要),但是必須將他們?cè)O(shè)置成同一個(gè)連接管理器,才能達(dá)到共用連接的目的。

參考文章:

Apache原文連接

原文翻譯

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

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

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