HttpClient4.1 使用示例
一、HttpClient簡介
HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,并且它支持 HTTP 協議最新的版本和建議。HttpClient 已經應用在很多的項目中,比如 Apache Jakarta 上很著名的另外兩個開源項目 Cactus 和 HTMLUnit 都使用了 HttpClient。現在HttpClient最新版本為 HttpClient 4.3.
二、HttpClient特性
- 基于標準,純凈的java語言.實現了Http1.0和Http1.1
- 以可擴展的面向對象的結構實現了Http全部的方法 (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE).
- 支持HTTPS協議.
- 通過Http代理建立透明的連接.
- 利用CONNECT 方法通過Http代理建立隧道的https連接.
- Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos 認證方案.
- 插件式的自定義認證方案.
- 便攜可靠的套接字工廠使它更容易的使用第三方解決方案.
- 連接管理器支持多線程應用.支持設置最大連接數,同時支持設置每個主機的最大連接數.發現并關閉過期的連接.
- Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.
- 插件式的自定義Cookie策略.
- Request output streams to avoid buffering any content body by streaming directly to the socket to the server.
- Response input streams to efficiently read the response body by streaming directly from the socket to the server.
- 在http1.0和http1.1中利用KeepAlive保持持久連接.
- 直接獲取服務器發送的response code和 headers.
- 設置連接超時的能力.
- 實驗性的支持http1.1 response caching.
- 源代碼基于Apache License 可免費獲取. </ol>
下載地址: http://hc.apache.org/downloads.cgi
三、詳細講解
這里為了更好的理解,新建了一個java se的工程,如下圖所示
HttpClientTest類