Spring整合httpclient

spring整合httpclient配置

①导入依赖
<!-- httpclient -->

<dependency>

        <groupId>org.apache.httpcomponents</groupId>

        <artifactId>httpclient</artifactId>

</dependency>

②spring整合httpclient配置

<!-- 配置连接管理器 -->

<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="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="requestConfig" class="org.apache.http.client.config.RequestConfig"

        factory-bean="requestConfigBuilder" factory-method="build">

</bean>

<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">

        <property name="connectionManager" ref="connectionManager"/>

</bean>

<!-- httpclient对象 -->

<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.service.httpclient.IdleConnectionEvictor" destroy-method="shutdown">

        <constructor-arg index="0" ref="connectionManager"/>

</bean>

下面是是为了位置线程管理无效连接

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(10000);
					// 关闭失效的连接
					connMgr.closeExpiredConnections();
				}
			}
		} catch (InterruptedException ex) {
			// 结束
		}
	}

	public void shutdown() {
		shutdown = true;
		synchronized (this) {
			notifyAll();
		}
	}
}

封装操作

@Service
public class HttpclientService {


    @Autowired(required = false)
    private CloseableHttpClient httpclient;


    @Autowired(required = false)
    private RequestConfig config;


    /**
     * 没有带参数doget
     * 
     * @throws Exception
     */
    public String doGet(String url) throws Exception {


        // 创建http GET请求
        HttpGet httpGet = new HttpGet(url);


        // 设置连接配置信息
        httpGet.setConfig(config);


        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");


            }
        } finally {
            if (response != null) {
                response.close();
            }
            // 已经交给线程清理
            // httpclient.close();
        }
        return null;
    }


    /**
     * 带有参数的doget请求
     */
    public String doGet(String url, Map<String, Object> params) throws Exception {


        // 定义请求的参数
        URIBuilder uriBuilder = new URIBuilder(url);


        if (!params.isEmpty()) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }
        URI uri = uriBuilder.build();


        // 创建http GET请求
        HttpGet httpGet = new HttpGet(uri);


        // 请求配置信息
        httpGet.setConfig(config);


        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } finally {
            if (response != null) {
                response.close();
            }
            // httpclient.close();
        }
        return null;
    }


    /**
     * 带参数doPost请求
     */
    public HttpResult doPost(String url, Map<String, Object> params) throws Exception {
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);


        // 设置2个post参数,一个是scope、一个是q
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(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, "UTF-8");
        // 将请求实体设置到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);
    }
    
    
    /**
     * 没有带参数doPost请求
     */
    public HttpResult doPost(String url) throws Exception{
        return this.doPost(url, null);
    }
    
    
    //TODO..留同学完成:  doput dodelete dopostjson  doputjson....


    /**
     * 指定POST请求
     * 
     * @param url
     * @param param 请求参数
     * @return 状态码和请求的body
     * @throws IOException
     */
    public HttpResult doPostJson(String url, String json) throws IOException {
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.config);
        if (json != null) {
            // 构造一个字符串的实体
            StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(stringEntity);
        }


        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            if (response.getEntity() != null) {
                return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                        response.getEntity(), "UTF-8"));
            }
            return new HttpResult(response.getStatusLine().getStatusCode(), null);
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }


    /**
     * 执行PUT请求
     * 
     * @param url
     * @param param 请求参数
     * @return 状态码和请求的body
     * @throws IOException
     */
    public HttpResult doPut(String url, Map<String, Object> param) throws IOException {
        // 创建http POST请求
        HttpPut httpPut = new HttpPut(url);
        httpPut.setConfig(config);
        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 formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
            // 将请求实体设置到httpPost对象中
            httpPut.setEntity(formEntity);
        }


        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPut);
            if (response.getEntity() != null) {
                return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                        response.getEntity(), "UTF-8"));
            }
            return new HttpResult(response.getStatusLine().getStatusCode(), null);
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }


    /**
     * 执行PUT请求
     * 
     * @param url
     * @return 状态码和请求的body
     * @throws IOException
     */
    public HttpResult doPut(String url) throws IOException {
        return this.doPut(url, null);
    }


    /**
     * 执行DELETE请求,通过POST提交,_method指定真正的请求方法
     * 
     * @param url
     * @param param 请求参数
     * @return 状态码和请求的body
     * @throws IOException
     */
    public HttpResult doDelete(String url, Map<String, Object> param) throws Exception {
        param.put("_method", "DELETE");
        return this.doPost(url, param);
    }


    /**
     * 执行DELETE请求(真正的DELETE请求)
     * 
     * @param url
     * @return 状态码和请求的body
     * @throws IOException
     */
    public HttpResult doDelete(String url) throws Exception {
        // 创建http DELETE请求
        HttpDelete httpDelete = new HttpDelete(url);
        httpDelete.setConfig(this.config);
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpDelete);
            if (response.getEntity() != null) {
                return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                        response.getEntity(), "UTF-8"));
            }
            return new HttpResult(response.getStatusLine().getStatusCode(), null);
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值