Httpclient4.4之原理(HttpClient接口)

HttpClient接口對於HTTP請求執行是關鍵。它對請求執行處理沒有限制,並且捨棄鏈接管理,狀態管理,認證和重定向到我的實現的那些方面的詳細細節。這讓使用附加功能修飾接口更容易了,例如response內容緩存。java

HttpClient接口的實現一般也做爲處理HTTP協議特定方面業務的Facade(參考Facade設計模式的定義),如重定向或認證處理或鏈接持久性決策和存活時間。這能夠讓用戶有選擇地使用自定義的程序在HttpClient上取代那些方面的默認實現。示例:設計模式

ConnectionKeepAliveStrategy keepAliveStrat = new DefaultConnectionKeepAliveStrategy() {
    @Override
    public long getKeepAliveDuration(HttpResponse response,HttpContext context) {
        long keepAlive = super.getKeepAliveDuration(response, context);
        if (keepAlive == -1) {
            /* Keep connections alive 5 seconds if a keep-alive value
             * has not be explicitly set by the server
             */
            keepAlive = 5000;
        }
        return keepAlive;
    }
}
CloseableHttpClient httpclient = HttpClients.custom().
    setKeepAliveStrategy(keepAliveStrat).build();

1. HttpClient線程安全緩存

HttpClient實現認爲是線程安全的,推薦這個類的同個實例用於多個請求。安全

2. HttpClient資源釋放ide

當CloseableHttpClient的實例再也不須要而且即將退出鏈接管理器的範圍, 它必須關閉。經過調用CloseableHttpClient的close()方法來關閉。ui

CloseableHttpClient httpclient = HttpClients.createDefault();
try {
    <...>
} finally {
    httpclient.close();
}
相關文章
相關標籤/搜索