HttpClient和spring整合
Posted 笙无望
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient和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"> <!-- 定义连接管理器 --> <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.taotao.web.httpclient.IdleConnectionEvictor"> <constructor-arg index="0" ref="httpClientConnectionManager" /> </bean> </beans>
封装ApiService
package com.taotao.web.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.ParseException; 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.web.httpclient.HttpResult; @Service public class ApiService implements BeanFactoryAware{ @Autowired private RequestConfig requestConfig; private BeanFactory beanFactory; /** * 指定GET请求,返回:null,请求失败,String数据,请求成功 * * @param url * @return * @throws ClientProtocolException * @throws IOException */ public String doGet(String url) throws ClientProtocolException, IOException { // 创建http GET请求 HttpGet httpGet = new HttpGet(url); httpGet.setConfig(requestConfig); CloseableHttpResponse response = null; try { // 执行请求 response = getHttpClient().execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { return EntityUtils.toString(response.getEntity(), "UTF-8"); } } finally { if (response != null) { response.close(); } } return null; } /** * 带有参数的GET请求,返回:null,请求失败,String数据,请求成功 * * @param url * @param params * @return * @throws ClientProtocolException * @throws IOException * @throws URISyntaxException */ public String doGet(String url, Map<String, String> params) throws ClientProtocolException, IOException, URISyntaxException { URIBuilder builder = new URIBuilder(url); for (Map.Entry<String, String> entry : params.entrySet()) { builder.setParameter(entry.getKey(), entry.getValue()); } return this.doGet(builder.build().toString()); } /** * 带有参数的POST请求 * * @param url * @param params * @return * @throws ParseException * @throws IOException */ public HttpResult doPost(String url, Map<String, String> params) throws ParseException, IOException { // 创建http POST请求 HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); if (null != params) { // 设置post参 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 = getHttpClient().execute(httpPost); return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString( response.getEntity(), "UTF-8")); } finally { if (response != null) { response.close(); } } } /** * 没有参数的POST请求 * * @param url * @return * @throws ParseException * @throws IOException */ public HttpResult doPost(String url) throws ParseException, IOException { return this.doPost(url, null); } private CloseableHttpClient getHttpClient(){ //通过Bean工厂获取bean,保证HttpClient对象是多例 return this.beanFactory.getBean(CloseableHttpClient.class); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } }
jar包
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.5</version> </dependency>
以上是关于HttpClient和spring整合的主要内容,如果未能解决你的问题,请参考以下文章
Spring+SpringMVC+MyBatis+Maven框架整合