項目中經常會用到模擬Http請求,而jdk 下的 rt.jar核心庫中也有 java.net提供了這方面的功能,但是總體而言,功能還是缺少靈活性和全面性,HttpClient的出現就是彌補了其缺失的功能。HttpClient不是瀏覽器客戶端,而是一個客戶端和服務端實現通信的Http組件庫。本篇文章主要講解CloseableHttpClient 的使用。
1. 項目中添加依賴的jar包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
<exclusions>
<exclusion>
<artifactId>commons-codec</artifactId>
<groupId>commons-codec</groupId>
</exclusion>
</exclusions>
</dependency>
2.1 模擬HttpGet請求
/**
* 模擬HttpGet 請求
* @param url
* @return
*/
public static String HttpGet(String url){
//單位毫秒
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(3000).setConnectTimeout(3000)
.setSocketTimeout(3000).build();//設置請求的狀態參數
CloseableHttpClient httpclient = HttpClients.createDefault();//創建 CloseableHttpClient
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpGet);//返回請求執行結果
int statusCode = response.getStatusLine().getStatusCode();//獲取返回的狀態值
if (statusCode != HttpStatus.SC_OK) {
return null;
} else {
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
return result;
}
} catch (Exception e) {
logger.error("httpget Exception handle-- > " + e);
} finally {
if (response != null){
try {
response.close();//關閉response
} catch (IOException e) {
logger.error("httpget IOException handle-- > " + e);
}
}
if(httpclient != null){
try {
httpclient.close();//關閉httpclient
} catch (IOException e) {
logger.error("httpget IOException handle-- > " + e);
}
}
}
return null;
}
2.2 模擬HttpPost請求
/**
* 模擬HttpPost請求
* @param url
* @param jsonString
* @return
*/
public static String HttpPost(String url, String jsonString){
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();//創建CloseableHttpClient
HttpPost httpPost = new HttpPost(url);//實現HttpPost
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
httpPost.setConfig(requestConfig); //設置httpPost的狀態參數
httpPost.addHeader("Content-Type", "application/json");//設置httpPost的請求頭中的MIME類型爲json
StringEntity requestEntity = new StringEntity(jsonString, "utf-8");
httpPost.setEntity(requestEntity);//設置請求體
try {
response = httpClient.execute(httpPost, new BasicHttpContext());//執行請求返回結果
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
String resultStr = EntityUtils.toString(entity, "utf-8");
return resultStr;
} else {
return null;
}
} catch (Exception e) {
logger.error("httpPost method exception handle-- > " + e);
return null;
} finally {
if (response != null){
try {
response.close();//最後關閉response
} catch (IOException e) {
logger.error("httpPost method IOException handle -- > " + e);
}
}if(httpClient != null){try {httpClient.close();} catch (IOException e) {logger.error("httpPost method exception handle-- > " + e);}
}
}
}