1.添加pom依賴
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
spring與httpclient的配置
2.spring-httpclient.xml
<?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">
<!-- 最大連接數(shù) -->
<property name="maxTotal" value="${http.maxTotal}" />
<!--設(shè)置每個主機最大的并發(fā)數(shù) -->
<property name="defaultMaxPerRoute" value="${http.defaultMaxPerRoute}" />
</bean>
<!--定義HttpClient構(gòu)建器 -->
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder"
factory-method="create">
<property name="connectionManager" ref="connectionManager" />
</bean>
<!--定義httpClient對象不傅,該bean一定是多例的 -->
<bean id="httpClient" class="org.apache.http.impl.client.CloseableHttpClient"
factory-bean="httpClientBuilder" factory-method="build" scope="prototype"></bean>
<!--定義requestConfig構(gòu)建器 -->
<bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">
<!--設(shè)置創(chuàng)建連接的最長時間 -->
<property name="connectTimeout" value="${http.connectTimeout}" />
<!--從連接池中獲取到連接的最長時間 -->
<property name="connectionRequestTimeout" value="${http.connectionRequestTimeout}" />
<!--數(shù)據(jù)傳輸?shù)淖铋L時間 -->
<property name="socketTimeout" value="${http.socketTimeout}" />
</bean>
<!--請求參數(shù)對象 -->
<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>
3.httpclient.properties(httpclient的屬性)
#設(shè)置連接總數(shù)
http.maxTotal=500
#設(shè)置每個主機最大的并發(fā)數(shù)
http.defaultMaxPerRoute=100
#設(shè)置創(chuàng)建連接的最長時間
http.connectTimeout=2000
#從連接池中獲取到連接的最長時間
http.connectionRequestTimeout=500
#數(shù)據(jù)傳輸?shù)淖铋L時間
http.socketTimeout=6000
#空閑時間(用于定期清理空閑連接)
http.maxIdleTime = 1
4.HttpClientService(httpclient請求服務(wù))
package com.dowin.httpclient;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
/**
* @ClassName: HttpClientService
* @Description: HttpClient請求工具
* @author kaifeng
* @date 2017年2月27日 下午5:33:10
*
*/
@Service
public class HttpClientService
{
@Autowired
private CloseableHttpClient httpClient;
@Autowired
private RequestConfig requestConfig;
/**
* @Title: doGet
* @Description: 執(zhí)行g(shù)et請求,200返回響應(yīng)內(nèi)容,其他狀態(tài)碼返回null
* @Author kaifeng
* @Date 2017年2月27日 下午5:24:09
* @param url 請求地址
* @return
* @throws IOException
* @throws
*/
public String doGet(String url) throws IOException
{
//創(chuàng)建httpClient對象
CloseableHttpResponse response = null;
HttpGet httpGet = new HttpGet(url);
//設(shè)置請求參數(shù)
httpGet.setConfig(requestConfig);
try
{
//執(zhí)行請求
response = httpClient.execute(httpGet);
//判斷返回狀態(tài)碼是否為200
if (response.getStatusLine().getStatusCode() == 200)
{
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
}
finally
{
if (response != null)
{
response.close();
}
}
return null;
}
/**
* @Title: doGet
* @Description: 執(zhí)行帶有參數(shù)的get請求
* @Author kaifeng
* @Date 2017年2月27日 下午5:24:33
* @param url 請求地址
* @param paramMap 參數(shù)鍵值對
* @return
* @throws IOException
* @throws URISyntaxException
* @throws
*/
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());
}
/**
* @Title: doPost
* @Description: 執(zhí)行post請求(有參數(shù))
* @Author kaifeng
* @Date 2017年2月27日 下午5:25:38
* @param url 請求地址
* @param paramMap 參數(shù)鍵值對
* @return
* @throws IOException
* @throws
*/
public HttpResult doPost(String url, Map<String, String> paramMap)
throws IOException
{
HttpPost httpPost = new HttpPost(url);
//設(shè)置請求參數(shù)
httpPost.setConfig(requestConfig);
if (paramMap != null)
{
List<NameValuePair> parameters = Lists.newArrayList();
for (String s : paramMap.keySet())
{
parameters.add(new BasicNameValuePair(s, paramMap.get(s)));
}
//構(gòu)建一個form表單式的實體
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
parameters, Charset.forName("UTF-8"));
//將請求實體放入到httpPost中
httpPost.setEntity(formEntity);
}
//創(chuàng)建httpClient對象
CloseableHttpResponse response = null;
try
{
//執(zhí)行請求
response = httpClient.execute(httpPost);
return new HttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity()));
}
finally
{
if (response != null)
{
response.close();
}
}
}
/**
* @Title: doPost
* @Description: 執(zhí)行post請求(無參數(shù))
* @Author kaifeng
* @Date 2017年2月27日 下午5:26:26
* @param url 請求地址
* @return
* @throws IOException
* @throws
*/
public HttpResult doPost(String url) throws IOException
{
return doPost(url, null);
}
/**
* @Title: doPostJson
* @Description: POST請求(JSON格式參數(shù))
* @Author kaifeng
* @Date 2017年2月27日 下午5:27:04
* @param url 請求地址
* @param json 請求參數(shù)為JSON格式
* @return
* @throws ClientProtocolException
* @throws IOException
* @throws
*/
public HttpResult doPostJson(String url, String json)
throws ClientProtocolException, IOException
{
// 創(chuàng)建http POST請求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(this.requestConfig);
if (json != null)
{
// 構(gòu)造一個請求實體
StringEntity stringEntity = new StringEntity(json,
ContentType.APPLICATION_JSON);
// 將請求實體設(shè)置到httpPost對象中
httpPost.setEntity(stringEntity);
}
CloseableHttpResponse response = null;
try
{
// 執(zhí)行請求
response = this.httpClient.execute(httpPost);
return new HttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(), "UTF-8"));
}
finally
{
if (response != null)
{
response.close();
}
}
}
}