添加相应依赖
配置
在applicationContext.xml中添加
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 创建连接管理器 -->
<bean id="httpClientConnectionManager"
class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">
<property name="maxTotal" value="${http.maxTotal}" />
<property name="defaultMaxPerRoute" value="${http.defaultMaxPerRoute}" />
</bean>
<!-- httpclient的构建器 -->
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">
<property name="connectionManager" ref="httpClientConnectionManager" />
</bean>
<!-- 创建Httpclient对象 -->
<!-- 该对象是多例的 -->
<bean class="org.apache.http.impl.client.CloseableHttpClient"
factory-bean="httpClientBuilder" factory-method="build" scope="prototype">
</bean>
<!-- 请求参数的构建器 -->
<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}" />
<!-- 提交请求前测试连接是否可用 -->
<property name="staleConnectionCheckEnabled" value="${http.staleConnectionCheckEnabled}" />
</bean>
<!-- 创建请求参数对象 -->
<bean class="org.apache.http.client.config.RequestConfig"
factory-bean="requestConfigBuilder" factory-method="build" />
<!-- 定期关闭无效连接 -->
<bean class="com.clc.web.httpclient.IdleConnectionEvictor">
<constructor-arg index="0" ref="httpClientConnectionManager" />
</bean>
</beans>
HttpClient实现跨域请求的service
package com.taotao.web.service;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.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.clc.web.bean.Result;//自建的包装类,包含状态码和响应数据
@Service
public class HttpClientService {
@Autowired
private RequestConfig config;
@Autowired
private CloseableHttpClient httpClient;
/**
* 无参的get请求
*
* @param url
* @return
*/
public String doGet(String url) {
// HttpGet对象
HttpGet get = new HttpGet(url);
get.setConfig(config);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(get);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "utf-8");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//httpClient.close();
//连接池会随着httpClientde的销毁而销毁,所以此处不能关闭httpClient
}
return null;
}
/**
* 有参的get请求
*
* @param url
* @return
*/
public String doGet(String url, Map<String, Object> params) {
List<NameValuePair> nvprs = new ArrayList<>();
// 遍历map
for (String key : params.keySet()) {
NameValuePair nvpr = new BasicNameValuePair(key, params.get(key).toString());
nvprs.add(nvpr);
}
CloseableHttpResponse response = null;
try {
URI uri = new URIBuilder(url).addParameters(nvprs).build();
// HttpGet对象
HttpGet get = new HttpGet(uri);
get.setConfig(config);
response = httpClient.execute(get);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "utf-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
// Save Update Delete (状态不同 返回值不一样? 有的有返回值 有的没有返回值。)
public Result doPost(String url, Map<String, Object> params) {
List<NameValuePair> nvprs = new ArrayList<>();
// 遍历map
for (String key : params.keySet()) {
NameValuePair nvpr = new BasicNameValuePair(key, params.get(key).toString());
nvprs.add(nvpr);
}
CloseableHttpResponse response = null;
try {
URI uri = new URIBuilder(url).addParameters(nvprs).build();
// HttpGet对象
HttpPost post = new HttpPost(uri);
post.setConfig(config);
response = httpClient.execute(post);
return new Result(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(), "utf-8"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
// Save Update Delete (状态不同 返回值不一样? 有的有返回值 有的没有返回值。)
public Result doPost(String url) {
CloseableHttpResponse response = null;
try {
// HttpGet对象
HttpPost post = new HttpPost(url);
post.setConfig(config);
response = httpClient.execute(post);
return new Result(response.getStatusLine().getStatusCode(),
EntityUtils.toString(response.getEntity(), "utf-8"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}