HttpClient的使用
一、介紹
HttpClient是Apache Jakarta Common下的子項目,用來提供高效的、最新的、功能豐富的支持HTTP協議的客戶端編程工具包,並且它支持HTTP協議最新的版本和建議。
二、使用方法
1、添加依賴
引入httpClient依賴
<!-- http通信 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.4</version>
</dependency>
####### 引入fastjson依賴
<!-- 解析json -->
<dependency>
<groupId>com.alibaba</groupId>
<version>1.2.62</version>
</dependency>
2、 編寫代碼
1、創建HttpClient對象。(推薦用CloseableHttpClient,HttpClient是歷史遺留版本,官方推薦使用CloseableHttpClient)
注:兩者的依賴不同
2、創建請求方法的實例,並指定請求uri。如果需要發送GET請求,創建HttpGet對象;如果需要發送POST請求,創建HttpPost對象。
3、如果需要發送請求參數,直接在請求地址后拼接參數(√);對於HttpPost對象而言,也可先設置參數隊列,然后調用setEntity(HttpEntity entity)方法來設置請求參數。
4、調用HttpClient對象的execute(HttpUriRequest request)發送請求,該方法返回一個HttpResponse/CloseableHttpResponse。
5、調用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務器的響應頭;調用HttpResponse的getEntity()方法可獲取HttpEntity對象,如果出現亂碼,可以將HttpEntity對象改成StringEntity,可通過該對象獲取服務器的響應內容。
6、釋放連接,無論方法是否執行成功,都應當必須釋放
@RequestMapping("/Crawling")
public String test() {
String file = wxCrawling.getFileurl();
UploadDto upload = useupdateService.gzhwebcontent(file);
//創建httpClient對象
CloseableHttpClient client = HttpClients.createDefault();
//將實體對象轉化為json格式對象
String uploadDto = JSON.toJSONString(upload);
//編寫訪問地址
String url = "http://192.168.18.109:9096//v1/wechat/upload";
//創建HttpPost請求
HttpPost post = new HttpPost(url);
try {
StringEntity stringEntity = new StringEntity(uploadDto, Charset.forName("UTF-8"));
//設置請求參數
post.setEntity(stringEntity);
//調用HttpClient對象的execute(HttpUriRequest request)發送請求,該方法返回一個HttpResponse/CloseableHttpResponse。
HttpResponse execute = client.execute(post);
System.out.println(execute);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file;
