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的更多相关文章
随机推荐
- input.file样式修改
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- mybatis LIKE
<sql id="selectId"> `ID` AS id, `NAME` AS name, `DESCRIPTION` AS description, `TYPE` ...
- adb 相关命令 以及无法adb识别设备的解决方法
[自己解决方法] 在-/.android/文件夹下面新建adb_usb.ini文件.里面写入设备的idVendor号(0x加上四位数字),然后输入 adb kill-server, 然后adb dev ...
- HDFS块文件和存放目录的关系
详情请参见DatanodeUtil.java中的函数idToBlockDir(File root, long blockId). 如果block文件没有放在正确的目录下,则DataNode会出现&qu ...
- C#窗体操作的小技巧
窗体在屏幕居中 ) - (), (Screen.GetBounds() - (), this.Width, this.Height, BoundsSpecified.Location);
- css3种引入方式,样式与长度颜色,常用样式,css选择器
# CSS三种引入方式 ## 一.三种方式的书写规范 #### 1.行间式 ```html<div style="width: 100px; height: 100px; backgr ...
- info AI drive
Who we look for Here at comma, we don't care about the source of your education or your traditional ...
- Keil_uvision 基本使用教程
Keil C51 V9.00 即09年发布的最新版本uVision 4,版本外观改变比较大,可以使用以前的注册文件.如果全新安装,在VISTA或者WIN 7系统下,请使用管理员方式运行,然后注册即可无 ...
- android-基础编程-RecyclerView
以后android-基础编程*都是控件demo里面的,不再累赘重写.直接介绍控件使用. RecyclerView is a more advanced and flexible version of ...
- android Activity中设置setResult 没有触发onActivityResult
昨天修改<manifest 文件中activity 的 模式为单例模式:android:launchMode="singleTask" ,发现我的onActivityResu ...