HttpClientUtil
package com.sinosoft.sms;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import java.util.*;
import javax.net.ssl.SSLContext;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
/**
* http、https请求
* @author zhaoman
* 2017-10-25
*
*/
public class HttpClientUtil {
private static final Logger logger = Logger.getLogger(HttpClientUtil.class);
private static PoolingHttpClientConnectionManager connMgr;
private static RequestConfig requestConfig;
private static final int ConnectMAXTIMEOUT = 8000; //连接超时时间
private static final int PoolMaxTotal = 100; //连接池大小
private static String encodeUTF8 = "UTF-8";
static {
// 设置连接池
connMgr = new PoolingHttpClientConnectionManager();
// 设置连接池大小
connMgr.setMaxTotal(PoolMaxTotal);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(ConnectMAXTIMEOUT);
// 设置读取超时
configBuilder.setSocketTimeout(ConnectMAXTIMEOUT);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(ConnectMAXTIMEOUT);
// 在提交请求之前 测试连接是否可用
configBuilder.setStaleConnectionCheckEnabled(true);
requestConfig = configBuilder.build();
}
/**
* 发送 GET 请求(HTTP),不带输入数据
* @param url
* @return
*/
public static String doGet(String url) {
return doGet(url, new HashMap<String, Object>());
}
/**
* 发送 GET 请求(HTTP),K-V形式
* @param url
* @param params
* @return
*/
public static String doGet(String url, Map<String, Object> params) {
String apiUrl = url;
StringBuffer param = new StringBuffer();
if(params != null && params.size() > 0) {
int i = 0;
for (String key : params.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
param.append(key).append("=").append(params.get(key));
i++;
}
apiUrl += param;
}
String result = null;
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpGet = new HttpGet(apiUrl);
HttpResponse response = httpclient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
logger.error("doGet statusCode : " + statusCode);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = IOUtils.toString(instream, encodeUTF8);
}
} catch (IOException e) {
logger.error("doGet is error", e);
}
return result;
}
/**
* 发送 POST 请求(HTTP),不带输入数据
* @param apiUrl
* @return
*/
public static String doPost(String apiUrl) {
return doPost(apiUrl, new HashMap<String, Object>());
}
/**
* 发送 POST 请求(HTTP),K-V形式
* @param apiUrl API接口URL
* @param params 参数map
* @return
*/
public static String doPost(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
if(params != null && params.size() > 0) {
List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName(encodeUTF8)));
}
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, encodeUTF8);
} catch (IOException e) {
logger.error("doPost is error", e);
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
logger.error("doPost consume is error", e);
}
}
}
return httpStr;
}
/**
* 发送 POST 请求(HTTP),JSON形式
* @param apiUrl
* @param json
* @return
*/
public static String doPost(String apiUrl, String jsonStr) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(requestConfig);
if(jsonStr != null) {
StringEntity stringEntity = new StringEntity(jsonStr,encodeUTF8);//解决中文乱码问题
stringEntity.setContentEncoding(encodeUTF8);
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
}
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
logger.error("Response Code : " + response.getStatusLine().getStatusCode());
}
httpStr = EntityUtils.toString(entity, encodeUTF8);
} catch (IOException e) {
logger.error("doPost is error", e);
//add by zzw 2020-02-19 BRM-3313 异常时,返回null
return null;
//end by zzw 2020-02-19
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
logger.error("doPost consume is error", e);
//add by zzw 2020-02-19 BRM-3313 异常时,返回null
return null;
//end by zzw 2020-02-19
}
}
}
return httpStr;
}
/**
* 发送 SSL POST 请求(HTTPS),K-V形式
* @param apiUrl API接口URL
* @param params 参数map
* @return
*/
public static String doPostSSL(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
String httpStr = null;
try {
httpPost.setConfig(requestConfig);
if(params != null && params.size() > 0) {
List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName(encodeUTF8)));
}
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
logger.info("Response Code : " + statusCode);
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, encodeUTF8);
} catch (Exception e) {
logger.error("doPostSSL is error", e);
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
logger.error("doPostSSL consume is error", e);
}
}
}
return httpStr;
}
/**
* 发送 SSL POST 请求(HTTPS),JSON形式
* @param apiUrl API接口URL
* @param json JSON字符串
* @return
*/
public static String doPostSSL(String apiUrl, String jsonStr) {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
String httpStr = null;
try {
httpPost.setConfig(requestConfig);
if(jsonStr != null) {
StringEntity stringEntity = new StringEntity(jsonStr, encodeUTF8);//解决中文乱码问题
stringEntity.setContentEncoding(encodeUTF8);
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
}
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
logger.info("Response Code : " + statusCode);
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, encodeUTF8);
} catch (Exception e) {
logger.error("doPostSSL is error", e);
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
logger.error("doPostSSL consume is error", e);
}
}
}
return httpStr;
}
/**
* 创建SSL安全连接
*
* @return
*/
public static SSLConnectionSocketFactory createSSLConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null;
try {
SSLContext sslContext;
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
//信任所有
@Override
public boolean isTrusted(X509Certificate[] xcs, String string){
return true;
}
}).build();
sslsf = new SSLConnectionSocketFactory(sslContext);
} catch (GeneralSecurityException e) {
logger.error("SSLConnectionSocketFactory is error", e);
}
return sslsf;
}
}

浙公网安备 33010602011771号