package com.foresee.zxpt.common.utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
/**
* https请求工具类
*
* @author GZ
*
*/
public class HttpsUtils {
protected static Log logger = LogFactory.getLog(HttpsUtils.class);
/**
* post请求 支持https 有证书和无证书
* @param url 请求url
* @param postData post表单
* @param header 请求头
* @param encoding 编码
* @param connectionTimeout 请求超时时间
* @param socketTimeout 传输超时时间
* @param isNoSSL 是否不带证书
* @return
* @throws UnsupportedEncodingException
* @throws Exception
*/
@SuppressWarnings("deprecation")
public static String doPostByClient(String url, Map<?, ?> postData, Map<?, ?> header, String encoding,
long connectionTimeout, long socketTimeout, boolean isNoSSL) {
CloseableHttpClient client=null;
try {
client = HttpClients.createDefault();
if (isNoSSL) {
client = (CloseableHttpClient) wrapClient(client);
}
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) socketTimeout)
.setConnectTimeout((int) connectionTimeout).build();// 设置请求和传输超时时
httpPost.setConfig(requestConfig);
// 头部请求信息
if (header != null) {
Set<?> entrySet = header.entrySet();
for (Iterator<?> itor = entrySet.iterator(); itor.hasNext();) {
Map.Entry entry = (Map.Entry) itor.next();
httpPost.addHeader(entry.getKey().toString(), entry.getValue().toString());
}
}
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
if (postData != null) {
Set<?> entrySet = postData.entrySet();
for (Iterator<?> itor = entrySet.iterator(); itor.hasNext();) {
Map.Entry entry = (Map.Entry) itor.next();
parameters.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue() + ""));
}
// 创建UrlEncodedFormEntity对象
UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, encoding);
httpPost.setEntity(formEntiry);
}
// 执行请求
CloseableHttpResponse response = client.execute(httpPost);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
response.close();
return result;
}
}
} catch (ConnectTimeoutException e) {
logger.error(e.getMessage());
// throw new UnsupportedEncodingException(e.getMessage());
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage());
// throw new UnsupportedEncodingException(e.getMessage());
} catch (ClientProtocolException e) {
logger.error(e.getMessage());
// throw new UnsupportedEncodingException(e.getMessage());
} catch (ParseException e) {
logger.error(e.getMessage());
// throw new UnsupportedEncodingException(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
// throw new UnsupportedEncodingException(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage());
// throw new UnsupportedEncodingException(e.getMessage());
}finally{
if(client!=null){
// 关闭HttpClient
client.getConnectionManager().shutdown();
}
}
return "";
}
/**
* 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常
* 不用导入SSL证书
*
* @param base
* @return
*/
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
ConnectionKeepAliveStrategy connectionKeepAliveStrategy = new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {
return 20 * 1000; // tomcat默认keepAliveTimeout为20s
}
};
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).setKeepAliveStrategy(connectionKeepAliveStrategy).build();
return httpclient;
} catch (Exception ex) {
logger.error(ex.getLocalizedMessage());
return HttpClients.createDefault();
}
}
}
x
180
1
package com.foresee.zxpt.common.utils;
2
3
import java.io.IOException;
4
import java.io.UnsupportedEncodingException;
5
import java.security.cert.CertificateException;
6
import java.security.cert.X509Certificate;
7
import java.util.ArrayList;
8
import java.util.Iterator;
9
import java.util.List;
10
import java.util.Map;
11
import java.util.Set;
12
13
import javax.net.ssl.SSLContext;
14
import javax.net.ssl.TrustManager;
15
import javax.net.ssl.X509TrustManager;
16
17
import org.apache.commons.logging.Log;
18
import org.apache.commons.logging.LogFactory;
19
import org.apache.http.HttpEntity;
20
import org.apache.http.HttpResponse;
21
import org.apache.http.NameValuePair;
22
import org.apache.http.ParseException;
23
import org.apache.http.client.ClientProtocolException;
24
import org.apache.http.client.HttpClient;
25
import org.apache.http.client.config.RequestConfig;
26
import org.apache.http.client.entity.UrlEncodedFormEntity;
27
import org.apache.http.client.methods.CloseableHttpResponse;
28
import org.apache.http.client.methods.HttpPost;
29
import org.apache.http.conn.ConnectTimeoutException;
30
import org.apache.http.conn.ConnectionKeepAliveStrategy;
31
import org.apache.http.conn.ssl.NoopHostnameVerifier;
32
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
33
import org.apache.http.impl.client.CloseableHttpClient;
34
import org.apache.http.impl.client.HttpClients;
35
import org.apache.http.message.BasicNameValuePair;
36
import org.apache.http.protocol.HttpContext;
37
import org.apache.http.util.EntityUtils;
38
39
/**
40
* https请求工具类
41
*
42
* @author GZ
43
*
44
*/
45
public class HttpsUtils {
46
47
protected static Log logger = LogFactory.getLog(HttpsUtils.class);
48
/**
49
* post请求 支持https 有证书和无证书
50
* @param url 请求url
51
* @param postData post表单
52
* @param header 请求头
53
* @param encoding 编码
54
* @param connectionTimeout 请求超时时间
55
* @param socketTimeout 传输超时时间
56
* @param isNoSSL 是否不带证书
57
* @return
58
* @throws UnsupportedEncodingException
59
* @throws Exception
60
*/
61
("deprecation")
62
public static String doPostByClient(String url, Map<?, ?> postData, Map<?, ?> header, String encoding,
63
long connectionTimeout, long socketTimeout, boolean isNoSSL) {
64
CloseableHttpClient client=null;
65
try {
66
client = HttpClients.createDefault();
67
if (isNoSSL) {
68
client = (CloseableHttpClient) wrapClient(client);
69
}
70
71
HttpPost httpPost = new HttpPost(url);
72
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) socketTimeout)
73
.setConnectTimeout((int) connectionTimeout).build();// 设置请求和传输超时时
74
httpPost.setConfig(requestConfig);
75
76
// 头部请求信息
77
if (header != null) {
78
Set<?> entrySet = header.entrySet();
79
for (Iterator<?> itor = entrySet.iterator(); itor.hasNext();) {
80
Map.Entry entry = (Map.Entry) itor.next();
81
httpPost.addHeader(entry.getKey().toString(), entry.getValue().toString());
82
}
83
}
84
85
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
86
87
if (postData != null) {
88
89
Set<?> entrySet = postData.entrySet();
90
91
for (Iterator<?> itor = entrySet.iterator(); itor.hasNext();) {
92
93
Map.Entry entry = (Map.Entry) itor.next();
94
95
parameters.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue() + ""));
96
97
}
98
99
// 创建UrlEncodedFormEntity对象
100
UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters, encoding);
101
102
httpPost.setEntity(formEntiry);
103
}
104
105
// 执行请求
106
107
CloseableHttpResponse response = client.execute(httpPost);
108
if(response.getStatusLine().getStatusCode()==200){
109
HttpEntity entity = response.getEntity();
110
if (entity != null) {
111
String result = EntityUtils.toString(entity);
112
response.close();
113
return result;
114
}
115
}
116
} catch (ConnectTimeoutException e) {
117
logger.error(e.getMessage());
118
// throw new UnsupportedEncodingException(e.getMessage());
119
} catch (UnsupportedEncodingException e) {
120
logger.error(e.getMessage());
121
// throw new UnsupportedEncodingException(e.getMessage());
122
} catch (ClientProtocolException e) {
123
logger.error(e.getMessage());
124
// throw new UnsupportedEncodingException(e.getMessage());
125
} catch (ParseException e) {
126
logger.error(e.getMessage());
127
// throw new UnsupportedEncodingException(e.getMessage());
128
} catch (IOException e) {
129
logger.error(e.getMessage());
130
// throw new UnsupportedEncodingException(e.getMessage());
131
} catch (Exception e) {
132
logger.error(e.getMessage());
133
// throw new UnsupportedEncodingException(e.getMessage());
134
}finally{
135
if(client!=null){
136
// 关闭HttpClient
137
client.getConnectionManager().shutdown();
138
}
139
}
140
return "";
141
}
142
143
/**
144
* 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”异常
145
* 不用导入SSL证书
146
*
147
* @param base
148
* @return
149
*/
150
public static HttpClient wrapClient(HttpClient base) {
151
try {
152
SSLContext ctx = SSLContext.getInstance("TLS");
153
X509TrustManager tm = new X509TrustManager() {
154
public X509Certificate[] getAcceptedIssuers() {
155
return null;
156
}
157
158
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
159
}
160
161
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
162
}
163
};
164
ctx.init(null, new TrustManager[] { tm }, null);
165
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
166
ConnectionKeepAliveStrategy connectionKeepAliveStrategy = new ConnectionKeepAliveStrategy() {
167
168
public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {
169
return 20 * 1000; // tomcat默认keepAliveTimeout为20s
170
}
171
};
172
173
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).setKeepAliveStrategy(connectionKeepAliveStrategy).build();
174
return httpclient;
175
} catch (Exception ex) {
176
logger.error(ex.getLocalizedMessage());
177
return HttpClients.createDefault();
178
}
179
}
180
}