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的更多相关文章
随机推荐
- 【Git】 GitLab服务器社区版安装与配置
GitLab简介 GitLab 是一个用于仓库管理系统的开源项目,使用Git作为代码管理工具,并在此基础上搭建起来的web服务 GitLab系统架构 当~git在图片中引用时,它表示git用户的主目录 ...
- MZOJ 1134: 二叉苹果树
按书上大的,dfs还需加强 #include <bits/stdc++.h> #define read read() using namespace std; int read { ; c ...
- ssh 常用命令
1.复制SSH密钥到目标主机,开启无密码SSH登录 ssh-copy-id user@host 如果还没有密钥,请使用ssh-keygen命令生成. 2.从某主机的80端口开启到本地主机2001端口的 ...
- 如何将字符串转化为Jsoup的Document 对象
有些时候在java操作解析html元素的时候比较繁琐,今天螃蟹就介绍一种可将html转换为document对象的方法——jsoup jsoup为我们解析html提供了比较全的API接口,我们通过将ht ...
- FMS是什么?
- Office2013 如何安装Matlab notebook
Office2013 如何安装Matlab notebook 听语音 浏览:912 | 更新:2014-09-16 07:02 1 2 3 4 5 6 7 分步阅读 Office2013(64bit) ...
- 安卓中的makefile文件打印调试信息
在安卓源码的makefile中有很多变量的值不方便确定,那么可以通过调试makefile文件来确定这些变量的值. $(warning " TARGET_BOARD_PLATFORM = ...
- 事件同步(一)-——CreateEvent( )事件对象实现线程同步
事件对象分为两类:人工重置事件对象和自动重置事件对象.对于人工重置事件对象,可以同时有多个线程等待到事件对象,成为可调度线程. 对于自动重置事件对象,等待该事件对象的多个线程只能有一个线程成为可调度线 ...
- java的静态内部类
只是一个简单的记录.因为一直排斥java这个东西.java跟c++比是很不错的一个语言,至少内存管理这么麻烦的东西不用操心了.但是和不断崛起的脚本语言比起来,效率差的太多.无论如何做android还是 ...
- Windows 8创新之路——样章分享
在电脑里面躺了大约也有半年多的光景了. 在Windows 8.1还有不到一个月的时间里,将这些内容分享出来,也算是对得起自己那段时间的熬夜. 希望大家多提宝贵意见. 谢! 点击标题可浏览SkyDriv ...