轉自:
http://www.java265.com/JavaCourse/202205/3545.html
下文筆者講述HTTPClient的示例分享,如下所示
HttpClient簡介
HTTPClient:
是Apache旗下的產品,基于HttpCore
HttpClient的官方參照檔案:http://hc.apache.org/httpcomponents-client-ga/tutorial/pdf/httpclient-tutorial.pdf
HttpClient使用步驟:
1.創建一個CloseableHttpClient實體
2.找一個可用的鏈接(uri)
3.執行httpclient.execute(uri)
4.response.close()
HttpClient的特性及優點
1. 基于java語言,實作了Http1.0和Http1.1 2. 以可擴展的面向物件的結構實作了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) 3. 支持HTTPS協議 4. 通過Http代理建立透明的連接 5. 利用CONNECT方法通過Http代理建立隧道的https連接 6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos認證方案 7. 插件式的自定義認證方案, 8. 便攜可靠的套接字工廠使它更容易的使用第三方解決方案 9. 連接管理器支持多執行緒應用,支持設定最大連接數,同時支持設定每個主機的最大連接數,發現并關閉過期的連接, 10. 自動處理Set-Cookie中的Cookie 11. 插件式的自定義Cookie策略 12. Request的輸出流可以避免流中內容直接緩沖到socket服務器 13. Response的輸入流可以有效的從socket服務器直接讀取相應內容 14. 在http1.0和http1.1中利用KeepAlive保持持久連接 15. 直接獲取服務器發送的response code和 headers 16. 設定連接超時的能力 17. 實驗性的支持http1.1 response caching 18. 源代碼基于Apache License 可免費獲取
例
使用HttpClient訪問指定url
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
<...>
} finally {
response.close();
}
例2:
spring中實體化CloseableHttpClient
@Autowired(required=false)
private CloseableHttpClient httpClient;
然后在spring里建一個xml檔案專門用于httpClient
關于URI的創建,官方提供了專門的api:
HttpClient provides URIBuilder utility class to simplify creation and modification of request URIs
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.google.com")
.setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "")
.build();
HttpGet httpget = new HttpGet(uri);
HttpEntity entity = response.getEntity();
例3:
get請求的示例
public String doGet(String url,Map<String, String> params,String encode) throws Exception {
if(null != params){
URIBuilder builder = new URIBuilder(url);
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.setParameter(entry.getKey(), entry.getValue());
}
url = builder.build().toString();
}
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
if(encode == null){
encode = "UTF-8";
}
return EntityUtils.toString(response.getEntity(), encode);
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/499957.html
標籤:Java
