基于HttpClient4.5.1实现Http访问工具类


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
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.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


/**
 * httpclient4
 *
 */
public class HttpClient {


private static Logger logger = LogManager.getLogger(HttpClient.class);


static final int TIMEOUT = 3 * 1000;


static final int SUCCESS_STATUS = 200;


static final String DEFAULT_CHATSET = "UTF-8";


private static final String DEFAULT_CONTENT_TYPE = "application/json";


private static CloseableHttpClient httpClient = null;


private final static Object syncLock = new Object();


private static void config(HttpRequestBase httpRequestBase) {
// 配置请求的超时设置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(TIMEOUT)
.setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();
httpRequestBase.setConfig(requestConfig);
}


/**
* 获取HttpClient对象
*/
public static CloseableHttpClient getHttpClient(String url) {
String hostname = url.split("/")[2];
int port = 80;
if (hostname.contains(":")) {
String[] arr = hostname.split(":");
hostname = arr[0];
port = Integer.parseInt(arr[1]);
}
if (httpClient == null) {
synchronized (syncLock) {
if (httpClient == null) {
httpClient = createHttpClient(hostname, port, 100, 10, 20);
}
}
}
return httpClient;
}


/**
* 创建HttpClient对象

* @return
* @author SHANHY
* @create 2015年12月18日
*/
public static CloseableHttpClient createHttpClient(String hostname,
int port, int maxTotal, int maxPerRoute, int maxRoute) {
ConnectionSocketFactory plainsf = PlainConnectionSocketFactory
.getSocketFactory();
LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory
.getSocketFactory();
Registry<ConnectionSocketFactory> registry = RegistryBuilder
.<ConnectionSocketFactory> create().register("http", plainsf)
.register("https", sslsf).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
registry);
// 将最大连接数增加
cm.setMaxTotal(maxTotal);
// 将每个路由基础的连接增加
cm.setDefaultMaxPerRoute(maxPerRoute);
HttpHost httpHost = new HttpHost(hostname, port);
// 将目标主机的最大连接数增加
cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);


CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm).build();


return httpClient;
}


private static void setPostParams(HttpPost httpost,
Map<String, Object> params) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
}
try {
httpost.setEntity(new UrlEncodedFormEntity(nvps, DEFAULT_CHATSET));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}


public static String doGet(String requestUrl) {
return doGet(requestUrl, DEFAULT_CHATSET);
}


/**
* GET请求URL获取内容
*/
public static String doGet(String requestUrl, String charset) {
String responseString = "";
long bgTime = System.currentTimeMillis();


HttpGet httpget = new HttpGet(requestUrl);
config(httpget);
CloseableHttpResponse response = null;
try {
response = getHttpClient(requestUrl).execute(httpget,
HttpClientContext.create());
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == SUCCESS_STATUS) {
responseString = readResponseBodyAsString(response.getEntity()
.getContent(), charset);
} else {
logger.error(
"Process reqeust failed, http response statusline is : {}",
response.getStatusLine());
}
} catch (Exception e) {
logger.error("Send request failed. ", e);
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
logger.error("Send request failed. ", e);
}
}
long costTime = System.currentTimeMillis() - bgTime;
logger.info("RP = {},CT = {}", responseString, costTime);
return responseString;
}

public static String doPost(String requestUrl, Map<String, Object> params) {
return doPost(requestUrl, params, DEFAULT_CHATSET);
}

/**
* POST请求URL获取内容

*/
public static String doPost(String requestUrl, Map<String, Object> params,
String charset) {
String responseString = "";
long bgTime = System.currentTimeMillis();


HttpPost httppost = new HttpPost(requestUrl);
config(httppost);
setPostParams(httppost, params);
CloseableHttpResponse response = null;


try {
response = getHttpClient(requestUrl).execute(httppost,
HttpClientContext.create());
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == SUCCESS_STATUS) {
responseString = readResponseBodyAsString(response.getEntity()
.getContent(), charset);
} else {
logger.error(
"Process reqeust failed, http response statusline is : {}",
response.getStatusLine());
}
} catch (Exception e) {
logger.error("Send request failed. ", e);
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
logger.error("Send request failed. ", e);
}
}
long costTime = System.currentTimeMillis() - bgTime;
logger.info("RP = {},CT = {}", responseString, costTime);
return responseString;
}


public static String doPostJosn(String requestUrl, String requestJsonString) {
return doPostJosn(requestUrl, requestJsonString, DEFAULT_CHATSET);
}


public static String doPostJosn(String requestUrl,
String requestJsonString, String charset) {
String responseString = "";
long bgTime = System.currentTimeMillis();


HttpPost httppost = new HttpPost(requestUrl);
config(httppost);
CloseableHttpResponse response = null;


try {
StringEntity requestEntity = new StringEntity(requestJsonString,
DEFAULT_CONTENT_TYPE);
httppost.setEntity(requestEntity);


response = getHttpClient(requestUrl).execute(httppost,
HttpClientContext.create());
int statusCode = response.getStatusLine().getStatusCode();


if (statusCode == SUCCESS_STATUS) {
responseString = readResponseBodyAsString(response.getEntity()
.getContent(), charset);
} else {
logger.error(
"Process reqeust failed, http response statusline is : {}",
response.getStatusLine());
}
} catch (Exception e) {
logger.error("Send request failed. ", e);
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
logger.error("Send request failed. ", e);
}
}
long costTime = System.currentTimeMillis() - bgTime;
logger.info("RP = {},CT = {}", responseString, costTime);
return responseString;
}


/**
* 将 response流读取为String。

* @param responseBody
* @return
* @throws Exception
*/
private static String readResponseBodyAsString(InputStream responseBody,
String charset) throws Exception {
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;


try {
reader = new BufferedReader(new InputStreamReader(responseBody,
charset == null ? DEFAULT_CHATSET : charset));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} catch (Exception e) {
throw e;
} finally {
try {
reader.close();
} catch (IOException e) {
throw e;
}
}


return buffer.toString();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值