applicationContext-httpclient
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 加载外部资源配置文件 -->
<context:property-placeholder location="classpath:properties/*.properties" />
<!-- 扫描Servcice -->
<context:component-scan base-package="com.sidekick.front" />
<bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">
<!-- 创建连接的最长时间 -->
<property name="connectTimeout" value="${httpclient.connectTimeout}" />
<!-- 从连接池中获取连接的最长时间 -->
<property name="connectionRequestTimeout" value="${httpclient.connectionRequestTimeout}" />
<!-- 数据传输的最长时间 -->
<property name="socketTimeout" value="${httpclient.socketTimeout}" />
<!-- 提交请求前,测试连接是否可用 -->
<property name="staleConnectionCheckEnabled" value="${httpclient.staleConnectionCheckEnabled}" />
</bean>
<!-- 配置连接管理器 -->
<bean id="connectionManager"
class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">
<property name="maxTotal" value="${httpclient.MaxTotal}" />
<property name="defaultMaxPerRoute" value="${httpclient.DefaultMaxPerRoute}" />
</bean>
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">
<!-- 设置连接管理器 -->
<property name="connectionManager" ref="connectionManager" />
</bean>
<bean id="httpClient" class="org.apache.http.impl.client.CloseableHttpClient"
factory-bean="httpClientBuilder" factory-method="build" scope="prototype">
</bean>
<!-- 配置清理连接对象 -->
<bean id="idleConnectionEvictor" class="com.atguigu.front.httpclient.IdleConnectionEvictor" destroy-method="shutdown">
<constructor-arg index="0" ref="connectionManager" />
</bean>
</beans>
HttpClientUtils
@Service
public class HttpClientUtils {
@Autowired(required = false)
private CloseableHttpClient httpclient;
@Autowired(required = false)
private RequestConfig config;
/**
* 没有带参数的get请求
*
* @param url
*请求地址
* @return 返回状态码为200, 返回页面内容,否则返回null
* @throws Exception
*/
public String doget(String url) throws Exception {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
response.close();
}
// httpclient.close();
}
return null;
}
/**
* 带有参数的get请求
*
* @param url
*请求地址
* @param params
*请求参数
* @return 返回状态码为200,返回页面,否则,返回null
* @throws Exception
*/
public String doget(String url, Map<String, Object> params)
throws Exception {
// 定义请求的参数
URIBuilder builder = new URIBuilder(url);
if (!params.isEmpty()) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
builder.setParameter(entry.getKey(), entry.getValue()
.toString());
}
}
URI uri = builder.build();
HttpGet httpGet = new HttpGet(uri);
// 设置请求参数
httpGet.setConfig(config);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
response.close();
}
// httpclient.close();
}
return null;
}
public HttpResult dopost(String url, Map<String, Object> params)
throws Exception {
// 创建HttpPost请求
HttpPost httpPost = new HttpPost(url);
// 设置2个post参数,一个是scope,一个是q
List<NameValuePair> parameters = new ArrayList<>(0);
if (!params.isEmpty()) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
parameters.add(new BasicNameValuePair(entry.getKey(), entry
.getValue().toString()));
}
}
// 构建一个form实体式的表单
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 将请求实体设置到HttpPost对象中
httpPost.setEntity(formEntity);
// 设置请求参数
httpPost.setConfig(config);
CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
return new HttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(), "UTF-8"));
}
} finally {
if (response != null) {
response.close();
}
// httpclient.close();
}
return new HttpResult(response.getStatusLine().getStatusCode(), null);
}
/**
* 没有带参数的post请求
* @param url
* @return
* @throws Exception
*/
public HttpResult dopost(String url) throws Exception {
return this.dopost(url, new HashMap<String, Object>());
}
/**
* 指定POST请求
* @param url
* @param json
* @return
* @throws Exception
*/
public HttpResult doPostJson(String url, String json) throws Exception{
//创建http POST请求
HttpPost post = new HttpPost(url);
post.setConfig(this.config);
if(json != null) {
//构造一个字符串的实体
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
//将请求实体设置到httppost对象中
post.setEntity(entity);
}
CloseableHttpResponse response = null;
try {
response = this.httpclient.execute(post);
if(response.getEntity() != null) {
return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(),"UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(response != null) {
response.close();
}
}
return new HttpResult(response.getStatusLine().getStatusCode(), null);
}
/**
*
* @param url
* @param param
* @return
* @throws Exception
*/
public HttpResult doPut(String url, Map<String, Object> param)
throws Exception {
// 创建http POST请求
HttpPut put = new HttpPut(url);
if (param != null) {
// 设置post参数
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
for (Map.Entry<String, Object> entry : param.entrySet()) {
parameters.add(new BasicNameValuePair(entry.getKey(), entry
.getValue().toString()));
}
// 构造一个form表单式的实体,并且指定其编码为UTF-8
UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(
parameters, "UTF-8");
// 将请求实体设置到httppost对象中
put.setEntity(encodedFormEntity);
}
// 执行请求
CloseableHttpResponse response = null;
try {
response = httpclient.execute(put);
if (response.getEntity() != null) {
return new HttpResult(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(), "UTF-8"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
response.close();
}
}
return new HttpResult(response.getStatusLine().getStatusCode(), null);
}
/**
* 执行PUT请求
* @param url
* @return
* @throws Exception
*/
public HttpResult doPut(String url) throws Exception {
return this.doPut(url, null);
}
/**
* 执行DELETE请求(真正的DELETE请求)
* @param url
* @return
* @throws Exception
*/
public HttpResult doDelete(String url) throws Exception {
//创建http DELET请求
HttpDelete delete = new HttpDelete(url);
delete.setConfig(this.config);
CloseableHttpResponse response = null;
try {
response = this.httpclient.execute(delete);
if(response.getEntity() != null) {
return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), "UTF-8"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(response != null) {
response.close();
}
}
return new HttpResult(response.getStatusLine().getStatusCode(), null);
}
/**
* 执行DELETE请求通过post提交,_method是真正的请求方法
* @param url
* @param param
* @return
* @throws Exception
*/
public HttpResult deDelete(String url, Map<String,Object> param) throws Exception {
param.put("_method", "DELETE");
return this.dopost(url, param);
}
}
httpclient.properties
httpclient.connectTimeout = 1000
httpclient.connectionRequestTimeout = 500
httpclient.socketTimeout = 10000
httpclient.staleConnectionCheckEnabled = true
httpclient.MaxTotal = 200
httpclient.DefaultMaxPerRoute = 20
HttpResult
public class HttpResult {
private Integer code;
private String body;
public HttpResult() {
super();
}
public HttpResult(Integer code, String body) {
super();
this.code = code;
this.body = body;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
@Override
public String toString() {
return "HttpResult [code=" + code + ", body=" + body + "]";
}
}