//IdleConnectionEvictor類
package com.mytaotao.common.bean; 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; } @Override public void run() { try { while (!shutdown) { synchronized (this) { wait(5000); // 關閉失效的連接 connMgr.closeExpiredConnections(); } } } catch (InterruptedException ex) { // 結束 } } public void shutdown() { shutdown = true; synchronized (this) { notifyAll(); } } }
<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>