HttpClilent整合Spring使用【配置和代码】

HttpClilent整合Spring使用【配置和代码】

  1. Spring配置
<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">

	<!-- 创建httpclient管理器 -->
	<bean id="connectionManager"
		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">
		<!-- 注入http_client管理器 -->
		<property name="ConnectionManager" ref="connectionManager" />
	</bean>

	<!--HttpCient对象 -->
	<bean id="httpclient" class="org.apache.http.impl.client.CloseableHttpClient"
		factory-bean="httpClientBuilder" factory-method="build" scope="prototype">
	</bean>

	<!-- 构建请求配置信息Builder -->
	<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 id="requestConfig" class="org.apache.http.client.config.RequestConfig"
		factory-bean="requestConfigBuilder" factory-method="build">
	</bean>
	
	<!--启动定时清理无效连接  -->
	<bean class="com.taotao.common.httpclient.IdleConnectionEvictor">
		<constructor-arg index="0" ref="connectionManager"/>
	</bean>
</beans>

  1. HttpClient工具类
package com.taotao.common.service;  

import java.io.IOException;
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.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.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.httpclient.HttpResult;

@Service
public class ApiService implements BeanFactoryAware{
    
//    @Autowired
//    private  CloseableHttpClient httpclient;
    
    @Autowired(required=false)
    private RequestConfig requestConfig;
    
    private BeanFactory beanFactory;
    
    /**
     * 200返回数据,其它为null
     * @author: kaixing  
     * @createTime: 2018年9月13日 下午10:40:00  
     * @history:  
     * @param url
     * @return
     * @throws ClientProtocolException
     * @throws IOException String
     */
    public String doGet(String url) throws ClientProtocolException, IOException{

        // 创建http GET请求
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(this.requestConfig);
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = createHttpClient().execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
    }
    
    /**
     * 带参数的get请求
     * @author: kaixing  
     * @createTime: 2018年9月13日 下午10:48:35  
     * @history:  
     * @param url
     * @param params
     * @return
     * @throws URISyntaxException
     * @throws ClientProtocolException
     * @throws IOException String
     */
    public String doGetParam(String url, Map<String,String> params) throws URISyntaxException, ClientProtocolException, IOException{
        // 定义请求的参数
        
        URIBuilder builder = new URIBuilder(url);
        for (Map.Entry<String, String> entry : params.entrySet()){
            builder.setParameter(entry.getKey(), entry.getValue());
        }
        return doGet(builder.build().toString());
        
    }
    
    /**
     * 带参数的post请求
     * @author: kaixing  
     * @createTime: 2018年9月14日 下午9:37:56  
     * @history:  
     * @param url
     * @param params
     * @return
     * @throws ClientProtocolException
     * @throws IOException HttpResult
     */
    public HttpResult doPost(String url, Map<String,String> params) throws ClientProtocolException, IOException{

        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
        // 设置2个post参数,一个是scope、一个是q
        if (null != params) {
            List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            // 构造一个form表单式的实体
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(formEntity);
        }
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = createHttpClient().execute(httpPost);
            return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), "UTF-8")) ;
        } finally {
            if (response != null) {
                response.close();
            }
        }
        
    }
    
    /**
     * 不带参数的post请求
     * @author: kaixing  
     * @createTime: 2018年9月14日 下午9:39:28  
     * @history:  
     * @param url
     * @return
     * @throws ClientProtocolException
     * @throws IOException HttpResult
     */
    public HttpResult doPost(String url) throws ClientProtocolException, IOException{
       return  this.doPost(url, null);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
            this.beanFactory = beanFactory;
    }
    
    private CloseableHttpClient createHttpClient(){
        return this.beanFactory.getBean(CloseableHttpClient.class);
    }
    
}
  
    
  1. 请求返回结果封装类
package com.taotao.common.httpclient;

public class HttpResult {
    
    private Integer code;
    
    private String body;
    
    

    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;
    }
    
    
}

  1. 开启线程回收无用连接
package com.taotao.common.httpclient;

import org.apache.http.conn.HttpClientConnectionManager;

public class IdleConnectionEvictor extends Thread {

    private final HttpClientConnectionManager connMgr;

    private volatile boolean shutdown;

    public IdleConnectionEvictor(HttpClientConnectionManager connMgr) {
        this.connMgr = connMgr;
        this.start();
    }

    @Override
    public void run() {
        try {
            while (!shutdown) {
                synchronized (this) {
                    wait(5000);
                    // 关闭失效的连接
                    connMgr.closeExpiredConnections();
                }
            }
        } catch (InterruptedException ex) {
            // 结束
        }
    }

    public void shutdown() {
        shutdown = true;
        synchronized (this) {
            notifyAll();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值