TmsHttpClientUtil

package com.sprucetec.tms.utils;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
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.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
* 发送http请求
* @author yangweiqiang
* @date 2016/10/12
*/
public class TmsHttpClientUtil {

private static Logger logger = Logger.getLogger(TmsHttpClientUtil.class);
private TmsHttpClientUtil(){}

//超时设置
private static final int DEFAULT_SOCKET_TIMEOUT = 60000;
private static final int DEFAULT_CONNECT_TIMEOUT = 30000;

//连接池最大数
private static final int POOL_MAX_TOTAL = 200;

private static CloseableHttpClient httpClient;
private static Object object = new Object();

public static CloseableHttpClient getHttpClient(){
if (null == httpClient){
synchronized (object){
if (null == httpClient){
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("https", createSSLConnSocketFactory())
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(POOL_MAX_TOTAL);

httpClient = HttpClients.custom().setConnectionManager(cm).build();
}
}
}
return httpClient;
}


/**
* 描述: 发送post请求并返回请求结构
* @param url 请求的url
* @param param 请求的参数
* @author yangweiqiang
* @date 2016/10/12
*/
public static String post(String url,String param){
if (null == url){
throw new RuntimeException("请求url不能为空!");
}

logger.info("TmsHttpClientUtil-POST:url = [" + url + "], param = [" + param + "]");

CloseableHttpClient httpClient = getHttpClient();// 获取httpclient
HttpPost post = getHttpPost(url);//获取httppost

post.setEntity(new StringEntity(param, "UTF-8"));//设置请求参数

CloseableHttpResponse response = null;
String result = null;//返回结果

try {
response = httpClient.execute(post);

//请求成功
if (response.getStatusLine().getStatusCode() == 200){
HttpEntity entity = response.getEntity();
if (entity!=null){
result = EntityUtils.toString(entity);
}
}else {
throw new IOException("返回HTTP状态码异常:" + response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
logger.error("TmsHttpClientUtil-exception:"+url,e);
throw new RuntimeException("请求发生异常!"+e.getMessage());
}finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
logger.error("TmsHttpClientUtil-关闭response异常:"+url,e);
}
}

return result;
}

/**
* 描述: 创建HttpPost
* @author yangweiqiang
* @date 2016/10/12
*/
private static HttpPost getHttpPost(String url) {
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json;charset=utf-8");
post.setHeader("Connection", "Keep-Alive");
RequestConfig config = RequestConfig.custom().setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT).build();
post.setConfig(config);
return post;
}

/**
* 创建SSL安全连接
*
* @return
*/
private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null;
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}

@Override
public void verify(String host, SSLSocket ssl) throws IOException {
}

@Override
public void verify(String host, X509Certificate cert) throws SSLException {
}

@Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
}
});
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
return sslsf;
}

}
原文地址:https://www.cnblogs.com/duyinqiang/p/6909863.html