HttpClient学习
httpCilent是apache的一个用于远程执行http方法的工具包,通过配置httpClient的pom包,并进行xml的配置,可以实现远程get post 等方式 调用其他工程的API。并且支持多线程调用.
- httpClient的pom坐标
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
2.httpClient的service类
public class ApiService implements BeanFactoryAware{
/**-------------注入需要的配置信息--------------------------**/
@Autowired(required = false)
private RequestConfig requestConfig;
//通过spring的beanFaoctory容器获取上下文bean CloseableHttpClient对象
private BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
private CloseableHttpClient getHttpClient(){
return this.beanFactory.getBean(CloseableHttpClient.class);
}
/**-------------get post 请求----------------**/
//无参数的get请求
public String doGet(String url){
HttpGet httpGet = new HttpGet(url);
//配置信息,由配置文件加载
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
response = getHttpClient().execute(httpGet);
if(response.getStatusLine().getStatusCode() == 200){
String content = EntityUtils.toString(response.getEntity(),"UTF-8");
return content;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
//后台发送请求获取数据
public String doGet(String url ,Map<String,String>params) throws URISyntaxException{
URIBuilder builder = new URIBuilder(url);
if(builder != null){
for (String key : params.keySet()) {
builder.setParameter(key, params.get(key));
}
}
URI uri = builder.build();
return this.doGet(uri.toString());
}
//带有参数的doPost请求
public HttpResult doPost(String url,Map<String,String> params) throws ClientProtocolException, IOException{
HttpPost httpPost = new HttpPost(url);
//设置entity
List<NameValuePair> parameters = new ArrayList<>();
for(String key : params.keySet()){
parameters.add(new BasicNameValuePair(key,params.get(key)));
}
httpPost.setConfig(requestConfig);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
//执行请求
response = getHttpClient().execute(httpPost);
Integer statusCodes = response.getStatusLine().getStatusCode();
String content = EntityUtils.toString(response.getEntity(),"UTF-8");
return new HttpResult(statusCodes,content);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(response !=null){
response.close();
}
}
return null;
}
//无参数的doPost请求
public HttpResult doPost(String url) throws IOException{
return this.doPost(url, null);
}
//发送带有josn格式字符串的post请求
public HttpResult doPostJson(String url,String json){
HttpPost httpPost = new HttpPost(url);
if(StringUtils.isNoneBlank(json)){
StringEntity entity = new StringEntity(json,ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
}
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
response = getHttpClient().execute(httpPost);
Integer statusCodes = response.getStatusLine().getStatusCode();
String content = EntityUtils.toString(response.getEntity(),"UTF-8");
return new HttpResult(statusCodes,content);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(response !=null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
3.spring整合httpClient的xml配置文件
----------
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!--主要配置四个地方
1.httpClientConnectionManager
2.CloseableHttpClient
3.RequestConfig
4.IdleConnectionEvictor --用于关闭无效连接
-->
<!--1. 配置http管理连接器,使用连接池管理器,功能更加强大-->
<bean id="httpClientConnectionManager" class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">
<property name="maxTotal" value="${httpclient.maxTotal}"/>
<property name="defaultMaxPerRoute" value="${httpclient.defaultMaxPerRoute}"/>
</bean>
<!--2.配置CloseableHttpClient>
<bean class="org.apache.http.impl.client.CloseableHttpClient" factory-bean = "httpClientBuilder" factory-method="build" scope="prototype">
</bean>
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">
<property name="connectionManager" ref="httpClientConntionManager">
</bean>
<!--3.配置requestConfig-->
<bean class="org.apache.http.client.config.RequestConfig" factory- bean="httpRequestConfig" factory-method="build">
</bean>
<bean id="httpRequestConfig" class="org.apache.http.client.config.RequestConfig.Builder">
<property name="connectTimeout" value="${httpclient.connectTimeout}"></property>
<property name="connectionRequestTimeout" value="${httpclient.connectionRequestTimeout}"></property>
<property name="socketTimeout" value="${httpclient.socketTimeout}"></property>
<property name="staleConnectionCheckEnabled" value="${httpclient.staleConnectionCheckEnabled}"></property>
</bean>
<!--4.配置IdleConnectionEvictor-->
<bean class="com.hw.httpclient.IdleConnectionEvictor">
<constructor-arg index="0" ref="httpClientConnectionManager"/>
</bean>
</bean>