本文整合基於httpclient目前最新版本4.5.1spring
首先加入httpclient的依賴apache
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
接下來spring-http的配置文件:json
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--定義鏈接管理器-->
<bean id="connectionManager" class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager"
destroy-method="close">
<!-- 最大鏈接數 -->
<property name="maxTotal" value="${http.maxTotal}"/>
<!--設置每一個主機最大的併發數-->
<property name="defaultMaxPerRoute" value="${http.defaultMaxPerRoute}"/>
</bean>併發
<!--定義HttpClient構建器-->
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder" factory-method="create">
<property name="connectionManager" ref="connectionManager"/>
</bean>socket
<!--定義httpClient對象,該bean必定是多例的-->
<bean id="httpClient" class="org.apache.http.impl.client.CloseableHttpClient" factory-bean="httpClientBuilder"
factory-method="build" scope="prototype"></bean>
<!--定義requestConfig構建器-->
<bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">
<!--設置建立鏈接的最長時間-->
<property name="connectTimeout" value="${http.connectTimeout}"/>
<!--從鏈接池中獲取到鏈接的最長時間-->
<property name="connectionRequestTimeout" value="${http.connectionRequestTimeout}"/>
<!--數據傳輸的最長時間-->
<property name="socketTimeout" value="${http.socketTimeout}"/>
</bean>
<!--請求參數對象-->
<bean class="org.apache.http.client.config.RequestConfig" factory-bean="requestConfigBuilder"
factory-method="build"></bean>
<!--按期清理無效鏈接-->
<bean class="org.apache.http.impl.client.IdleConnectionEvictor" destroy-method="shutdown">
<constructor-arg index="0" ref="connectionManager"/>
<constructor-arg index="1" value="${http.maxIdleTime}"/>
<constructor-arg index="2" value="MINUTES"/>
</bean>
</beans>
httpclient.properties的配置文件:工具
#設置鏈接總數
http.maxTotal=500
#設置每一個主機最大的併發數
http.defaultMaxPerRoute=100
#設置建立鏈接的最長時間
http.connectTimeout=2000
#從鏈接池中獲取到鏈接的最長時間
http.connectionRequestTimeout=500
#數據傳輸的最長時間
http.socketTimeout=6000
#空閒時間(用於按期清理空閒鏈接)
http.maxIdleTime = 1
httpclient封裝的工具類:post
@Service
public class ApiService {
@Autowired
private CloseableHttpClient httpClient;
@Autowired
private RequestConfig requestConfig;ui
/**
* 執行get請求,200返回響應內容,其餘狀態碼返回null
*
* @param url
* @return
* @throws IOException
*/
public String doGet(String url) throws IOException {
//建立httpClient對象
CloseableHttpResponse response = null;
HttpGet httpGet = new HttpGet(url);
//設置請求參數
httpGet.setConfig(requestConfig);
try {
//執行請求
response = httpClient.execute(httpGet);
//判斷返回狀態碼是否爲200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}this
/**
* 執行帶有參數的get請求
*
* @param url
* @param paramMap
* @return
* @throws IOException
* @throws URISyntaxException
*/
public String doGet(String url, Map<String, String> paramMap) throws IOException, URISyntaxException {
URIBuilder builder = new URIBuilder(url);
for (String s : paramMap.keySet()) {
builder.addParameter(s, paramMap.get(s));
}
return doGet(builder.build().toString());
}url
/**
* 執行post請求
*
* @param url
* @param paramMap
* @return
* @throws IOException
*/
public HttpResult doPost(String url, Map<String, String> paramMap) throws IOException {
HttpPost httpPost = new HttpPost(url);
//設置請求參數
httpPost.setConfig(requestConfig);
if (paramMap != null) {
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (String s : paramMap.keySet()) {
parameters.add(new BasicNameValuePair(s, paramMap.get(s)));
}
//構建一個form表單式的實體
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, Charset.forName("UTF-8"));
//將請求實體放入到httpPost中
httpPost.setEntity(formEntity);
}
//建立httpClient對象
CloseableHttpResponse response = null;
try {
//執行請求
response = httpClient.execute(httpPost);
return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity()));
} finally {
if (response != null) {
response.close();
}
}
}
/**
* 執行post請求
*
* @param url
* @return
* @throws IOException
*/
public HttpResult doPost(String url) throws IOException {
return doPost(url, null);
}
/**
* 提交json數據
*
* @param url
* @param json
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public HttpResult doPostJson(String url, String json) throws ClientProtocolException, IOException {
// 建立http POST請求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(this.requestConfig);
if (json != null) {
// 構造一個請求實體
StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
// 將請求實體設置到httpPost對象中
httpPost.setEntity(stringEntity);
}
CloseableHttpResponse response = null;
try {
// 執行請求
response = this.httpClient.execute(httpPost);
return new HttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(), "UTF-8"));
} finally {
if (response != null) {
response.close();
}
}
}
}
http執行post請求返回的封裝類:
public class HttpResult {
private Integer code;
private String data;
public HttpResult(Integer code, String data) {
this.code = code;
this.data = data;
}
public HttpResult() {
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getData() {
return data;
}
public void setData(String data) { this.data = data; } }