1 添加依赖
2添加配置文件
<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="${httpclient.maxTotal}"/>
<!-- 设置每个主机地址的并发数 -->
<property name="defaultMaxPerRoute" value="${httpclient.defaultMaxPerRoute}"/>
</bean>
<bean id="builder" 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="requestConfig" class="org.apache.http.client.config.RequestConfig"
factory-bean="builder" factory-method="build"/>
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">
<!--设置请求头信息配置 -->
<property name="defaultRequestConfig" ref="requestConfig"/>
<!--设置连接管理器 -->
<property name="connectionManager" ref="httpClientConnectionManager"/>
</bean>
<bean class="org.apache.http.impl.client.CloseableHttpClient"
factory-bean="httpClientBuilder" factory-method="build" />
<!-- 定期关闭失效连接 -->
<bean class="com.taotao.common.bean.IdleConnectionEvictor" destroy-method="shutdown">
<constructor-arg index="0" ref="httpClientConnectionManager"/>
</bean>
</beans>
properties
httpclient.connectTimeout=1000
httpclient.connectionRequestTimeout=500
httpclient.socketTimeout=10000
httpclient.staleConnectionCheckEnabled=true
httpclient.maxTotal=200
httpclient.defaultMaxPerRoute=20
=============
1封装apiService:
ApiService:
package com.taotao.common.service;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.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.taotao.common.bean.HttpclientResult;
/**
* 使用Httpclient调用接口的工具类
* @author Henry
*
*/
@Service
public class ApiService {
//需要去Spring 容器中注册 httpclient对象
@Autowired(required=false)
private CloseableHttpClient httpclient;
// public ApiService(CloseableHttpClient httpclient) {
// super();
// this.httpclient = httpclient;
// }
/**
* 无参的Get请求
* @param url
* @throws ClientProtocolException
* @throws IOException
*/
public String doGet(String url) throws ClientProtocolException, IOException{
HttpGet httpGet = new HttpGet(url);
//调用接口后响应对象 : 响应状态 响应内容
CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200 响应状态码
if (response.getStatusLine().getStatusCode() == 200) {
//说明请求成功,能够正确得到响应结果
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
return content;
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
/**
* 有参的get请求
* @param url
* @param Map<参数名称,参数值> params
* @return
* @throws ClientProtocolException
* @throws IOException
* @throws URISyntaxException
*/
public String doGetParam(String url,Map<String,String> params) throws ClientProtocolException, IOException, URISyntaxException{
// 定义请求的参数
URIBuilder uriBuilder = new URIBuilder(url);
if(params != null && !params.isEmpty()){
for(String key : params.keySet()){
uriBuilder.setParameter(key, params.get(key));
}
}
//build方法创建出URI对象
URI uri = uriBuilder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
//调用接口后响应对象 : 响应状态 响应内容
CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200 响应状态码
if (response.getStatusLine().getStatusCode() == 200) {
//说明请求成功,能够正确得到响应结果
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
return content;
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
/**
*
* @param url
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public HttpclientResult doPost(String url) throws ClientProtocolException, IOException{
// 创建http POST请求 输入URL
HttpPost httpPost = new HttpPost(url);
//模拟了浏览器来进行访问
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
CloseableHttpResponse response = null;
try {
// 执行请求 敲回车
response = httpclient.execute(httpPost);
String data = EntityUtils.toString(response.getEntity(), "UTF-8");
return new HttpclientResult(response.getStatusLine().getStatusCode(), data);
} finally {
if (response != null) {
response.close();
}
}
}
/**
* 有参的Post请求
* @param url
* @param Map<参数名称,参数值> params
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public HttpclientResult doPostParam(String url,Map<String,String> params) throws ClientProtocolException, IOException{
// 创建http POST请求
HttpPost httpPost = new HttpPost(url);
if(params != null && !params.isEmpty()){
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
for(String key : params.keySet()){
parameters.add(new BasicNameValuePair(key, params.get(key)));
}
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 将请求实体设置到httpPost对象中 设置post请求提交的表单
httpPost.setEntity(formEntity);
}
//模拟了浏览器来进行访问
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
CloseableHttpResponse response = null;
try {
// 执行请求 敲回车
response = httpclient.execute(httpPost);
String data = EntityUtils.toString(response.getEntity(), "UTF-8");
return new HttpclientResult(response.getStatusLine().getStatusCode(), data);
} finally {
if (response != null) {
response.close();
}
}
}
}
HttpclientResult(返回结果的封装)
package com.taotao.common.bean;
public class HttpclientResult {
//响应状态码
private Integer code;
//响应数据
private String data;
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;
}
public HttpclientResult(Integer code, String data) {
super();
this.code = code;
this.data = data;
}
}
2 在项目项目中的使用:
测试:
扫描二维码关注公众号,回复:
3930392 查看本文章
注入ApiService ,然后调用里边的方法,获得数据
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext*.xml")
public class ApiServiceTest {
@Autowired
private ApiService apiService;
@Test
public void testDoGetString() throws IOException {
String content = this.apiService.doGet("http://www.baidu.com");
System.out.println(content);
}
@Test
public void testDoGetStringMapOfStringString() throws Exception {
Map<String,String> params = new HashMap<>();
params.put("categoryId", "13");
params.put("rows", "6");
params.put("callback", "func");
String content = this.apiService.doGet("http://manage.taotao.com/rest/api/content",params);
System.out.println(content);
}
@Test
public void testDoPostStringMapOfStringString() throws ParseException, IOException {
Map<String,String> params = new HashMap<>();
params.put("scope", "project");
params.put("q", "java");
params.put("fromerr", "8bDnUWwC");
String content = this.apiService.doPost("http://www.oschina.net/search", params);
System.out.println(content);
}
@Test
public void testDoPostString() {
fail("Not yet implemented");
}
}