Httpclient多執行緒連線池封裝
阿新 • • 發佈:2019-02-07
1、封裝
package com.suning.search.utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CommonHttpClient {
private static final Logger log = LoggerFactory.getLogger(CommonHttpClient.class);
private static final String CHARSET = "UTF-8";
private static Map<ClientName, HttpClient> clientMap = new HashMap<ClientName, HttpClient>(
ClientName.values().length);
public static int HTTP_CONNECT_TIMEOUT = 5000;
public static int HTTP_SO_TIMEOUT = 5000;
public static int HTTP_POOL_TIMEOUT = 1000;
public static int HTTP_MAX_ROUTE_CONNECTIONS = 128;
public static int HTTP_MAX_TOTAL_CONNECTIONS = 10;
private CommonHttpClient() {
}
public static void initHttpClients() {
clientMap.clear();
}
/**
* http client模組名稱的列舉類
*/
public static enum ClientName {
DEFAULT_CLIENT
}
public static class ClientParam {
private int poolTimeout;
private int connectionTimeout;
private int soTimeout;
private int maxRouteConnections;
private int maxTotalConnections;
public ClientParam(int poolTimeout, int connectionTimeout,
int soTimeout, int maxRouteConnections, int maxTotalConnections) {
this.poolTimeout = poolTimeout;
this.connectionTimeout = connectionTimeout;
this.soTimeout = soTimeout;
this.maxRouteConnections = maxRouteConnections;
this.maxTotalConnections = maxTotalConnections;
}
public int getPoolTimeout() {
return poolTimeout;
}
public void setPoolTimeout(int poolTimeout) {
this.poolTimeout = poolTimeout;
}
public int getConnectionTimeout() {
return connectionTimeout;
}
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public int getSoTimeout() {
return soTimeout;
}
public void setSoTimeout(int soTimeout) {
this.soTimeout = soTimeout;
}
public int getMaxRouteConnections() {
return maxRouteConnections;
}
public void setMaxRouteConnections(int maxRouteConnections) {
this.maxRouteConnections = maxRouteConnections;
}
public int getMaxTotalConnections() {
return maxTotalConnections;
}
public void setMaxTotalConnections(int maxTotalConnections) {
this.maxTotalConnections = maxTotalConnections;
}
@Override
public String toString() {
return "ClientParam [poolTimeout=" + poolTimeout
+ ", connectionTimeout=" + connectionTimeout
+ ", soTimeout=" + soTimeout + ", maxRouteConnections="
+ maxRouteConnections + ", maxTotalConnections="
+ maxTotalConnections + "]";
}
}
/**
* 根據http client名稱獲取對應的引數
*
* @param clientName CommonHttpClient.HTTP_SPES_INTERFACE_CLIENT,
* CommonHttpClient.SUNING_DOMAIN_CLIENT
* @return ClientParam
*/
private static ClientParam getClientParam(ClientName clientName) {
ClientParam param = null;
switch (clientName) {
// default httpclient 初始化引數
case DEFAULT_CLIENT:
param = new ClientParam(HTTP_POOL_TIMEOUT,
HTTP_CONNECT_TIMEOUT,
HTTP_SO_TIMEOUT,
HTTP_MAX_ROUTE_CONNECTIONS,
HTTP_MAX_TOTAL_CONNECTIONS);
break;
default:
param = new ClientParam(HTTP_POOL_TIMEOUT,
HTTP_CONNECT_TIMEOUT,
HTTP_SO_TIMEOUT,
HTTP_MAX_ROUTE_CONNECTIONS,
HTTP_MAX_TOTAL_CONNECTIONS);
break;
}
return param;
}
/**
* 建立httpclient
*/
@SuppressWarnings("deprecation")
public static synchronized HttpClient createHttpClient(ClientName clientName) {
HttpClient httpClient = clientMap.get(clientName);
if (httpClient != null) {
return httpClient;
}
ClientParam clientParam = getClientParam(clientName);
HttpParams params = new BasicHttpParams();
// 設定一些基本引數
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProtocolParams
.setUserAgent(
params,
"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
// 超時設定
/* 從連線池中取連線的超時時間 */
/* 連線超時 */
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
clientParam.getConnectionTimeout());
/* 請求超時 */
params.setParameter(CoreConnectionPNames.SO_TIMEOUT,
clientParam.getSoTimeout());
params.setParameter(CoreConnectionPNames.SO_KEEPALIVE,"true");
// 設定我們的HttpClient支援HTTP和HTTPS兩種模式
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", 80, PlainSocketFactory
.getSocketFactory()));
schReg.register(new Scheme("https", 443, SSLSocketFactory
.getSocketFactory()));
// 使用執行緒安全的連線管理來建立HttpClient
PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(
schReg);
// MAX_ROUTE_CONNECTIONS為要設定的每個路由最大連線數
pccm.setDefaultMaxPerRoute(clientParam.getMaxRouteConnections());
pccm.setMaxTotal(clientParam.getMaxTotalConnections());
HttpClient client = new DefaultHttpClient(pccm, params);
clientMap.put(clientName, client);
return client;
}
/**
* 根據http客戶端名獲取相應的連線例項
*
* @param clientName
* @return
*/
public static HttpClient getHttpClient(ClientName clientName) {
HttpClient httpClient = clientMap.get(clientName);//由於在類的初始化時並沒有賦值,所以必定為null
if (null == httpClient) {
httpClient = createHttpClient(clientName);
}
return httpClient;
}
public static String get(String url, ClientName clientName) {
try {
HttpGet httpget = new HttpGet(url);
HttpResponse response = getHttpClient(clientName).execute(httpget);
HttpEntity httpEntity = response.getEntity();
String result = null;
if (httpEntity != null) {
result = EntityUtils.toString(httpEntity);
EntityUtils.consume(httpEntity);
}
return result;
} catch (UnsupportedEncodingException e) {
<