-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathHttpTools.java
executable file
·650 lines (607 loc) · 19.9 KB
/
HttpTools.java
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
package com.luckin.stock.utils;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.SSLContext;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
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.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
/**
* Http请求管理 说明:
*
* @author zheng_zhi_rui@163com
* @date 2015年3月25日
*
*/
public class HttpTools {
private static final int TIMEOUT = 5000;
private static Logger logger = LoggerFactory.getLogger(HttpTools.class);
/**
* Get请求,兼容https
*
* @param url
* @param params
* @return
* @throws URISyntaxException
* @throws Exception
*/
public static JSONObject doGet(String url, Map<String, String> params) {
if(StringUtil.isBlankOrEmpty(url)){
return null;
}
if(url.startsWith("https")){
return doSSLGet(url, params);
}
CloseableHttpClient httpClient = HttpClients.custom().build();
JSONObject jsonData = null;
try {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT)
.setConnectionRequestTimeout(TIMEOUT).build();
URI uri = null;
URIBuilder uriBuilder = new URIBuilder();
if (params != null && params.size() > 0) {
Set<String> keys = params.keySet();
Iterator<String> it = keys.iterator();
for (; it.hasNext();) {
String key = it.next();
String val = params.get(key);
uriBuilder.setParameter(key, val);
}
}
uri = uriBuilder.build();
HttpGet httpGet = new HttpGet(url + uri);
// System.out.println(url + uri);
httpGet.setConfig(requestConfig);
jsonData = httpClient.execute(httpGet, createResponseHandler());
} catch (Exception e1) {
e1.printStackTrace();
return jsonData;
} finally {
try {
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonData;
}
/**
* POST请求,兼容https
*
* @param url
* @param params
* @return
* @throws IOException
* @throws ClientProtocolException
*/
public static JSONObject doPost(String url, Map<String, String> params) {
if(StringUtil.isBlankOrEmpty(url)){
return null;
}
if(url.startsWith("https")){
return doSSLPost(url, params);
}
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT)
.setConnectionRequestTimeout(TIMEOUT).build();
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
if (params != null && params.size() > 0) {
for (Map.Entry<String, String> entry : params.entrySet()) {
paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
logger.info("invoke other service,url ---> {}", url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
JSONObject jsonData = null;
CloseableHttpClient httpClient = HttpClients.custom().build();
try {
jsonData = httpClient.execute(httpPost, createResponseHandler());
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
return jsonData;
} finally {
try {
if(httpClient != null){
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonData;
}
/**
* POST请求,传输二进制数据
*
* @param url
* @param content
* @return
*/
public static String writeBinaryPost(String url, Map<String, String> params, String content, String charset,
boolean encode) {
try {
/*
* 拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码
*/
String get_url = url;
if (url != null && url.lastIndexOf("?") == -1)
get_url += "?";
if (params != null && params.size() > 0)
for (String key : params.keySet()) {
get_url += key + "=";
if (encode) {
get_url += URLEncoder.encode(params.get(key), charset) + "&";
} else {
get_url += params.get(key) + "&";
}
}
if (params != null && params.size() > 0)
get_url = get_url.substring(0, get_url.lastIndexOf('&'));
URL postUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("contentType", charset);
connection.setRequestProperty("Content-Type", "binary/octet-stream");
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
/* out.writeBytes(); 在转换的时候会造成中文乱码 */
out.write(content.getBytes(charset));
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
String line = "";
String responseContent = "";
for (; (line = reader.readLine()) != null;) {
responseContent += line;
}
reader.close();
connection.disconnect();
return responseContent;
} catch (Exception e) {
return "";
}
}
public static JSONObject doPost(String url, Map<String, String> params, Map<String, String> header) {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT)
.setAuthenticationEnabled(true).setConnectionRequestTimeout(TIMEOUT).build();
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
if (params != null && params.size() > 0) {
for (Map.Entry<String, String> entry : params.entrySet()) {
paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
HttpPost httpPost = new HttpPost(url);
if (header != null && header.size() > 0) {
Set<String> keySet = header.keySet();
for (String key : keySet) {
httpPost.addHeader(key, header.get(key));
}
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpPost.setConfig(requestConfig);
JSONObject jsonData = null;
CloseableHttpClient httpClient = HttpClients.custom().build();
try {
jsonData = httpClient.execute(httpPost, createResponseHandler());
} catch (Exception e) {
e.printStackTrace();
return jsonData;
} finally {
try {
if(httpClient != null){
httpClient.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonData;
}
/**
* GET 请求 HTTPURLConnection实现
*
* @param url
* @param params
* @param charset
* @return
* @throws IOException
*/
public static String urlGet(String url, Map<String, String> params, String charset, boolean encode) {
try {
/*
* 拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码
*/
String get_url = url;
String paramStr = "";
if (params != null && params.size() > 0) {
for (String key : params.keySet()) {
paramStr += key + "=";
if (encode) {
paramStr += URLEncoder.encode(params.get(key), charset) + "&";
} else {
paramStr += params.get(key) + "&";
}
}
}
if (params != null && params.size() > 0) {
paramStr = paramStr.substring(0, paramStr.lastIndexOf('&'));
if (url != null && url.lastIndexOf("?") == -1) {
get_url += "?" + paramStr;
}
}
URL getUrl = new URL(get_url);
/*
* 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,
* 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
*/
HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
/*
* 进行连接,但是实际上get
* request要在下一句的connection.getInputStream()函数中才会真正发到服务器
*/
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
String line = "";
String responseContent = "";
for (; (line = reader.readLine()) != null;) {
responseContent += line;
}
reader.close();
connection.disconnect();
return responseContent;
} catch (Exception e) {
// logger.error("msg:"+e);
// e.printStackTrace();
return "";
}
}
/**
* POST 请求 HTTPURLConnection实现
*
* @param url
* @param params
* @return
* @throws IOException
*/
public static String urlPost(String url, Map<String, String> params, String charset, boolean lineFlag) {
try {
logger.info("invoke other service ,url-->{}", url);
URL postUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
/*
* 设置是否向connection输出,因为这个是post请求,参数要放在 http正文内,因此需要设为true
*/
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
/*
* Post 请求不能使用缓存
*/
connection.setUseCaches(false);
/* URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。 */
/* URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数 */
connection.setInstanceFollowRedirects(true);
/*
* 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
* 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
* 进行编码
*/
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
/*
* 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成.
* 要注意的是connection.getOutputStream会隐含的进行connect。
*/
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
/*
* 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
*/
String content = "";
if (params != null && params.size() > 0)
for (String key : params.keySet()) {
content += key + "=" + URLEncoder.encode(params.get(key), "UTF-8") + "&";
}
if (params != null && params.size() > 0)
content = content.substring(0, content.lastIndexOf('&'));
/*
* DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
*/
out.writeBytes(content);
out.flush();
out.close();
/*
* 设置编码,否则中文乱码
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
String line = "";
String responseContent = "";
for (; (line = reader.readLine()) != null;) {
if (lineFlag) {
responseContent += "\r\n" + line;
} else {
responseContent += line;
}
}
reader.close();
connection.disconnect();
return responseContent;
} catch (Exception e) {
return "";
}
}
/**
* SSL安全认证请求 测试方法
*
* @param url
* @param params
* @return
*/
@SuppressWarnings("deprecation")
public static void SSLPost(String url, String params) {
final String KEYSTORE_FILE = "";
final String TRUSTSTORE_FILE = "";
final String KEYSTORE_PASSWORD = "";
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
File file = new File("");
FileInputStream fis = new FileInputStream(file);
keyStore.load(fis, "nopassword".toCharArray());
fis.close();
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, new TrustSelfSignedStrategy())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpPost httpget = new HttpPost(url);
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String httpClientGet(String url) {
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(url);
String res = "";
try {
int st = client.executeMethod(get);
if (st == 200) {
res = get.getResponseBodyAsString();
} else {// 请求失败,重新请求一遍
st = client.executeMethod(get);
res = get.getResponseBodyAsString();
}
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
private static ResponseHandler<JSONObject> createResponseHandler() {
ResponseHandler<JSONObject> jsonHandler = new ResponseHandler<JSONObject>() {
public JSONObject handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
// StatusLine statusCode = response.getStatusLine();
// if (statusCode.getStatusCode() >= 300) {
// throw new HttpResponseException(statusCode.getStatusCode(),
// statusCode.getReasonPhrase());
// }
HttpEntity httpEntity = response.getEntity();
if (httpEntity == null) {
throw new ClientProtocolException("Response contains no content");
}
ContentType contentType = ContentType.getOrDefault(httpEntity);
Charset charset = contentType.getCharset();
if (charset == null) {
charset = Consts.UTF_8;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
"UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
for (; (line = reader.readLine()) != null;) {
buffer.append(line + "\n");
}
// System.out.println(buffer.toString());
return JSONObject.parseObject(buffer.toString());
}
};
return jsonHandler;
}
/**
* 发送https协议的Get请求
* @param url
* @return
*/
public static JSONObject doSSLGet(String url, Map<String, String> params) {
CloseableHttpClient httpClient = createSSLClientDefault();
JSONObject jsonData = null;
try {
//定义
HttpGet httpGet = new HttpGet();
//设置URL
URIBuilder uriBuilder = new URIBuilder(url);
if(params != null){
for (String key : params.keySet()) {
uriBuilder.setParameter(key, params.get(key));
}
}
URI uri = uriBuilder.build();
httpGet.setURI(uri);
//设置连接超时、响应时间
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(TIMEOUT)
.setConnectTimeout(TIMEOUT)
.build();
httpGet.setConfig(config);
//执行请求,获取响应
logger.debug("executing request" + httpGet.getRequestLine());
jsonData = httpClient.execute(httpGet, createResponseHandler());
return jsonData;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
try {
if(httpClient != null){
httpClient.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonData;
}
/**
* 发送https协议的Post请求
* @param url
* @return
*/
public static JSONObject doSSLPost(String url, Map<String, String> params) {
CloseableHttpClient httpClient = createSSLClientDefault();
JSONObject jsonData = null;
try {
//定义
HttpPost httpPost = new HttpPost();
//设置URL
URIBuilder uriBuilder = new URIBuilder(url);
if(params != null){
for (String key : params.keySet()) {
uriBuilder.setParameter(key, params.get(key));
}
}
URI uri = uriBuilder.build();
httpPost.setURI(uri);
//设置连接超时、响应时间
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(TIMEOUT)
.setConnectTimeout(TIMEOUT)
.build();
httpPost.setConfig(config);
//执行请求,获取响应
logger.debug("executing request" + httpPost.getRequestLine());
jsonData = httpClient.execute(httpPost, createResponseHandler());
return jsonData;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
try {
if(httpClient != null){
httpClient.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonData;
}
/**
* 信任所有证书
* @return
*/
private static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
null, new TrustStrategy() {
// 信任所有
@Override
public boolean isTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
// TODO Auto-generated method stub
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
}