HttpUtil.java
14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package com.zteits.job.util;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
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.HttpGet;
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.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.BufferedHttpEntity;
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.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class HttpUtil {
private static Certificate cert = null;
private static SSLConnectionSocketFactory socketFactory;//私密连接工厂
private static TrustManager manager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
/**
* 是否忽略证书.https网站一般情况下使用了安全系数较低的SHA-1签名,因此首先我们在调用SSL之前需要重写验证方法,取消检测SSL。
*/
private static void enableSSl(boolean isIgnore) {
try {
SSLContext context = SSLContext.getInstance("TLS");
if (isIgnore) {
context.init(null, new TrustManager[]{manager}, null);
} else {
context.init(null, new TrustManager[]{httpsManager}, null);
}
socketFactory = new SSLConnectionSocketFactory(context, NoopHostnameVerifier
.INSTANCE);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
/**
* 证书获取
*
* @param certificateUrl 证书地址.
*/
private static void initHttpsCertificate(String certificateUrl) {
try {
FileInputStream fis = new FileInputStream(certificateUrl);
BufferedInputStream bis = new BufferedInputStream(fis);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
cert = cf.generateCertificate(bis);
}
bis.close();
} catch (IOException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
}
}
private static TrustManager httpsManager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{(X509Certificate) cert};
}
};
/**
* httpClient get http 请求.
*
* @param url 请求路径.
* @param values 请求参数.
* @return response 请求结果状态.
*/
public static String doGet(String url, List<NameValuePair> values) throws IOException {
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
//最新版的httpClient使用实现类的是closeableHTTPClient,以前的default作废了.设置可关闭的httpclient
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
StringBuilder urlBuffer = new StringBuilder(url);
if (!url.contains("?")) {
urlBuffer.append("?");
}
if (values != null) {
for (NameValuePair nameValuePair : values) {
urlBuffer.append("&").append(nameValuePair.getName()).append("=")
.append(URLEncoder.encode(nameValuePair.getValue(), "UTF-8"));
}
}
HttpGet get = new HttpGet(urlBuffer.toString());
CloseableHttpResponse response = httpClient.execute(get);
return getResponseContent(response);
}
/**
* httpClient post http 请求.
*
* @param url 请求路径.
* @param values 请求参数.
* @return response 请求结果状态.
*/
public static String doPost(String url, List<NameValuePair> values) throws IOException {
/*Map<String,String> paramMap = new HashMap<String, String>();
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
for (Map.Entry<String,String> entry : paramMap.entrySet()){
formParams.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}*/
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
HttpPost post = new HttpPost(url);
if (values != null) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, "UTF-8");
//StringEntity entity = new StringEntity(values);
post.setEntity(entity);
}
CloseableHttpResponse response = httpClient.execute(post);
return getResponseContent(response);
}
/**
* httpClient post http 请求.
*
* @param url
* @param values
* @param charset
* @return
* @throws IOException
*/
public static String doPost(String url, List<NameValuePair> values, String charset) throws IOException {
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
HttpPost post = new HttpPost(url);
if (charset == null) {
charset = "UTF-8";
}
if (values != null) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, charset);
//StringEntity entity = new StringEntity(values);
post.setEntity(entity);
}
CloseableHttpResponse response = httpClient.execute(post);
return getResponseContent(response);
}
/**
* httpClient get https 请求.
*
* @param url 请求路径.
* @param values 请求参数.
* @return response 请求结果状态.
*/
public static String ignoreGetForHttps(String url, List<NameValuePair> values, boolean isIgnoreSSL) throws
IOException {
enableSSl(isIgnoreSSL);
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
.setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,
AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC))
.build();
//创建可用Scheme
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
//创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new
PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(config).build();
StringBuilder urlBuffer = new StringBuilder(url);
if (!url.contains("?")) {
urlBuffer.append("?");
}
if (values != null) {
for (NameValuePair nameValuePair : values) {
urlBuffer.append("&").append(nameValuePair.getName()).append("=")
.append(URLEncoder.encode(nameValuePair.getValue(), "UTF-8"));
}
}
HttpGet get = new HttpGet(urlBuffer.toString());
CloseableHttpResponse response = httpClient.execute(get);
return getResponseContent(response);
}
/**
* httpClient get https 请求.
*
* @param url 请求路径.
* @return response 请求结果状态.
*/
public static String ignoreGetForHttps(String url, boolean isIgnoreSSL) throws
IOException {
enableSSl(isIgnoreSSL);
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
.setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,
AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC))
.build();
//创建可用Scheme
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
//创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new
PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(config).build();
HttpGet get = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(get);
return getResponseContent(response);
}
/**
* httpClient post https 请求.
*
* @param url 请求路径.
* @param values 请求参数.
* @return response 请求结果状态.
*/
public static String ignorePostForHttps(String url, List<NameValuePair> values, boolean isIgnoreSSL)
throws IOException {
enableSSl(isIgnoreSSL);
//首先设置全局的标准cookie策略
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
.setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,
AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC))
.build();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
PoolingHttpClientConnectionManager connectionManager = new
PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(config).build();
HttpPost post = new HttpPost(url);
if (values != null) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Charset.forName("UTF-8"));
post.setEntity(entity);
}
CloseableHttpResponse response = httpClient.execute(post);
return getResponseContent(response);
}
/**
* httpClient post https 请求.
*
* @param url 请求路径.
* @param values 请求参数.
* @return response 请求结果状态.
*/
public static String ignorePostForHttps(String url, JSONObject jsonParam, boolean isIgnoreSSL)
throws IOException {
enableSSl(isIgnoreSSL);
//首先设置全局的标准cookie策略
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
.setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,
AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC))
.build();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
PoolingHttpClientConnectionManager connectionManager = new
PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(config).build();
HttpPost post = new HttpPost(url);
if (null != jsonParam) {
//解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
}
CloseableHttpResponse response = httpClient.execute(post);
return getResponseContent(response);
}
/**
* 获取请求返回值.
*/
private static String getResponseContent(CloseableHttpResponse response)
throws IOException {
StringBuilder returnBuffer = new StringBuilder();
BufferedReader reader = null;
try {
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
HttpEntity httpEntity = response.getEntity();
httpEntity = new BufferedHttpEntity(httpEntity);
return EntityUtils.toString(httpEntity);
}
} finally {
response.close();
}
return null;
}
}