歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Httpclient4.4之原理(HttpClient接口)

Httpclient4.4之原理(HttpClient接口)

日期:2017/3/1 9:29:04   编辑:Linux編程

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

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資源釋放

當CloseableHttpClient的實例不再需要並且即將退出連接管理器的范圍, 它必須關閉。通過調用CloseableHttpClient的close()方法來關閉。

CloseableHttpClient httpclient = HttpClients.createDefault();
try {
<...>
} finally {
httpclient.close();
}

使用HttpClient實現文件的上傳下載 http://www.linuxidc.com/Linux/2014-07/104303.htm

Android 實現 HttpClient 請求Https http://www.linuxidc.com/Linux/2014-05/102306.htm

Android使用HttpClient下載圖片 http://www.linuxidc.com/Linux/2014-05/101855.htm

HttpClient使用詳解 http://www.linuxidc.com/Linux/2014-08/104945.htm

Copyright © Linux教程網 All Rights Reserved