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;
} }
TmsHttpClientUtil的更多相关文章
随机推荐
- 进度条的制作unity
			不说了直接上代码: LoadingPanel: using UnityEngine;using System.Collections;using UnityEngine.UI;using UnityE ... 
- 有关PHP 10条有用的建议--转(柒捌玖零)
			1.使用ip2long() 和long2ip()函数来把IP地址转化成整型存储到数据库里. 这种方法把存储空间降到了接近四分之一(char(15)的15个字节对整形的4个字节),计算一个特定的地址是不 ... 
- 高性能Java RPC框架Dubbo与zookeeper的使用
			https://blog.csdn.net/qq_38982845/article/details/83795295 
- BZOJ 1024 [SCOI2009]生日快乐 (搜索)
			1024: [SCOI2009]生日快乐 Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 3025 Solved: 2201[Submit][Statu ... 
- oracle忘记了sys,system 密码后怎么修改?
			一.忘记除SYS.SYSTEM用户之外的用户的登录密码. 用SYS (或SYSTEM)用户登录: CONN SYS/PASS_WORD AS SYSDBA; 使用如下语句修改用户的密码: ALTE ... 
- php 验证码 图像存在错误 无法显示 解决方法
			<?php $height = 300; $width = 300; $im = imagecreatetruecolor($width, $height); $white = imagecol ... 
- jQuery length 和 size()区别
			jQuery length和size()区别总结如下: 1.length是属性,size()是方法. 2.如果你只是想获取元素的个数,两者效果一样既 $("img").length ... 
- 理解-const
			c++ 中const和c中define的区别 (1) 编译器处理方式不同 define宏是在预处理阶段展开. const常量是编译运行阶段使用. (2) 类型和安全检查不同 define宏没有类型,不 ... 
- AngularJS的select设置默认值
			AngularJS的select设置默认值 在使用Angular时候使用select标签时会遇到绑定数据指定默认显示值可这样实现 <!DOCTYPE html> <html ng-a ... 
- POJ1195--Mobile phones(基础二维BIT)
			Description Suppose that the fourth generation mobile phone base stations in the Tampere area operat ... 
