-
Notifications
You must be signed in to change notification settings - Fork 1
/
HttpUtil.java
1067 lines (1014 loc) · 34.6 KB
/
HttpUtil.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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cn.xanderye.util;
import lombok.Data;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
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.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
/**
* http请求工具 返回对象包括状态码、响应头、cookie和响应体,自行根据状态码判断
* 默认不使用连接池,需要请调用 enableConnectionPool
*
* @author XanderYe
* @date 2020/2/4
*/
public class HttpUtil {
/**
* 默认请求超时
*/
private static final int DEFAULT_CONNECT_TIMEOUT = 30000;
/**
* 默认读取超时
*/
private static final int DEFAULT_SOCKET_TIMEOUT = 30000;
/**
* 默认重试次数
*/
private static final int DEFAULT_RETRY_COUNT = 3;
/**
* 默认最大连接数
*/
private static final int DEFAULT_MAX_TOTAL = 200;
/**
* 默认单个路由最大连接数
*/
private static final int DEFAULT_MAX_PER_ROUTE = 100;
/**
* 默认清空空闲连接 秒
*/
private static final int DEFAULT_IDLE_TIMEOUT = 5;
/**
* 默认定时器间隔 秒
*/
private static final int DEFAULT_MONITOR_PERIOD = 30;
/**
* 默认编码
*/
private static final String CHARSET = "UTF-8";
/**
* 默认请求头
*/
private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36";
/**
* 基本请求路径
*/
private static String baseUrl = "";
/**
* 是否使用代理
*/
private static boolean enableProxy = false;
private static String proxyIp = "127.0.0.1";
private static int proxyPort = 8888;
/**
* 是否自动重定向
*/
private static boolean redirect = false;
/**
* 是否重试
*/
private static boolean enableRetry = false;
/**
* 连接超时
*/
private static int connectTimeout;
/**
* 读取超时
*/
private static int socketTimeout;
/**
* 重试次数
*/
private static int retryCount;
/**
* 最大连接数
*/
private static int maxTotal;
/**
* 单个路由最大连接数
*/
private static int maxPerRoute;
/**
* 清空空闲连接 秒
*/
private static int idleTimeout;
/**
* 定时器间隔 秒
*/
private static int monitorPeriod;
/**
* 是否启用连接池
*/
private static AtomicBoolean connectionPool = new AtomicBoolean(false);
/**
* 连接池httpClient对象
*/
private static volatile CloseableHttpClient httpClient;
/**
* 连接池配置
*/
private static volatile PoolingHttpClientConnectionManager connectionManager;
/**
* 定时器
*/
private static volatile ScheduledExecutorService monitorExecutor;
// 静态代码块初始化配置
static {
socketTimeout = DEFAULT_SOCKET_TIMEOUT;
connectTimeout = DEFAULT_CONNECT_TIMEOUT;
retryCount = DEFAULT_RETRY_COUNT;
maxTotal = DEFAULT_MAX_TOTAL;
maxPerRoute = DEFAULT_MAX_PER_ROUTE;
idleTimeout = DEFAULT_IDLE_TIMEOUT;
monitorPeriod = DEFAULT_MONITOR_PERIOD;
}
/**
* 获取客户端
* @param
* @return void
* @author XanderYe
* @date 2021/5/24
*/
private static CloseableHttpClient getHttpClient() {
// 启用了连接池配置,直接返回全局客户端
if (connectionPool.get()) {
return httpClient;
}
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.setCookieSpec(CookieSpecs.IGNORE_COOKIES)
.setRedirectsEnabled(redirect)
.build();
return custom().setDefaultRequestConfig(config).build();
}
/**
* 初始化连接池配置
* @param
* @return void
* @author XanderYe
* @date 2022/1/21
*/
private static void initPoolingHttpClient() {
if (httpClient == null) {
synchronized (HttpUtil.class) {
if (httpClient == null) {
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.setCookieSpec(CookieSpecs.IGNORE_COOKIES)
.setRedirectsEnabled(redirect)
.build();
connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(maxTotal);
connectionManager.setDefaultMaxPerRoute(maxPerRoute);
httpClient = custom().setDefaultRequestConfig(config).setConnectionManager(connectionManager).build();
connectionPool.set(true);
//开启监控线程,对异常和空闲线程进行关闭
monitorExecutor = Executors.newScheduledThreadPool(1);
monitorExecutor.scheduleAtFixedRate(() -> {
//关闭异常连接
connectionManager.closeExpiredConnections();
//关闭空闲的连接
connectionManager.closeIdleConnections(idleTimeout, TimeUnit.SECONDS);
}, 0, monitorPeriod, TimeUnit.SECONDS);
}
}
}
}
/**
* 创建httpClientBuilder
*
* @return org.apache.http.impl.client.HttpClientBuilder
* @author XanderYe
* @date 2020/2/14
*/
private static HttpClientBuilder custom() {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
// 忽略证书
httpClientBuilder.setSSLSocketFactory(ignoreCertificates());
if (enableProxy) {
// 使用代理
httpClientBuilder.setProxy(new HttpHost(proxyIp, proxyPort));
}
if (enableRetry) {
// 使用重试机制
httpClientBuilder.setRetryHandler(retryHandler());
}
return httpClientBuilder;
}
/**
* GET请求
*
* @param url
* @param params
* @return cn.xanderye.util.HttpUtil.ResEntity
* @author XanderYe
* @date 2020-03-15
*/
public static ResEntity doGet(String url, Map<String, Object> params) throws IOException {
return doGet(url, null, null, params);
}
/**
* POST请求
*
* @param url
* @param params
* @return cn.xanderye.util.HttpUtil.ResEntity
* @author XanderYe
* @date 2020-03-15
*/
public static ResEntity doPost(String url, Map<String, Object> params) throws IOException {
return doPost(url, null, null, params);
}
/**
* POST提交JSON请求
* @param url
* @param jsonString
* @return cn.xanderye.util.HttpUtil.ResEntity
* @author XanderYe
* @date 2020/10/22
*/
public static ResEntity doPostJSON(String url, String jsonString) throws IOException {
return doPostJSON(url, null, null, jsonString);
}
/**
* POST提交XML请求
* @param url
* @param xml
* @return cn.xanderye.util.HttpUtil.ResEntity
* @author XanderYe
* @date 2020/12/10
*/
public static ResEntity doPostXML(String url, String xml) throws IOException {
return doPostXML(url, null, null, xml);
}
/**
* get请求基础方法
*
* @param url
* @param headers
* @param params
* @return cn.xanderye.util.HttpUtil.ResEntity
* @author XanderYe
* @date 2020/2/4
*/
public static ResEntity doGet(String url, Map<String, Object> headers, Map<String, Object> cookies, Map<String, Object> params) throws IOException {
url = baseUrl + url;
// 拼接参数
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
String value = entry.getValue() == null ? null : (entry.getValue()).toString();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
try {
String parameters = EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET));
String symbol = url.contains("?") ? "&" : "?";
// 判断是否已带参数
url += symbol + parameters;
} catch (IOException e) {
e.printStackTrace();
}
}
HttpGet httpGet = new HttpGet(url);
// 添加headers
addHeaders(httpGet, headers);
// 添加cookies
addCookies(httpGet, cookies);
HttpClientContext httpClientContext = new HttpClientContext();
CloseableHttpClient httpClient = getHttpClient();
try (CloseableHttpResponse response = httpClient.execute(httpGet, httpClientContext)) {
return getResEntity(response, false);
} finally {
if (!connectionPool.get()) {
httpClient.close();
}
}
}
/**
* 检查URL
* @param url
* @param headers
* @param cookies
* @param params
* @return int
* @author XanderYe
* @date 2023/12/6
*/
public static CheckEntity doCheck(String url, Map<String, Object> headers, Map<String, Object> cookies, Map<String, Object> params) throws IOException {
url = baseUrl + url;
// 拼接参数
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
String value = entry.getValue() == null ? null : (entry.getValue()).toString();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
try {
String parameters = EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET));
String symbol = url.contains("?") ? "&" : "?";
// 判断是否已带参数
url += symbol + parameters;
} catch (IOException e) {
e.printStackTrace();
}
}
HttpGet httpGet = new HttpGet(url);
// 添加headers
addHeaders(httpGet, headers);
// 添加cookies
addCookies(httpGet, cookies);
HttpClientContext httpClientContext = new HttpClientContext();
CloseableHttpClient httpClient = getHttpClient();
long start = System.currentTimeMillis();
try (CloseableHttpResponse response = httpClient.execute(httpGet, httpClientContext)) {
long end = System.currentTimeMillis();
CheckEntity checkEntity = new CheckEntity();
checkEntity.setStatusCode(response.getStatusLine().getStatusCode());
checkEntity.setDelay(end - start);
return checkEntity;
} finally {
if (!connectionPool.get()) {
httpClient.close();
}
}
}
/**
* post请求基础方法
*
* @param url
* @param headers
* @param params
* @return cn.xanderye.util.HttpUtil.ResEntity
* @author XanderYe
* @date 2020/2/4
*/
public static ResEntity doPost(String url, Map<String, Object> headers, Map<String, Object> cookies, Map<String, Object> params) throws IOException {
HttpPost httpPost = new HttpPost(baseUrl + url);
// 拼接参数
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
String value = entry.getValue() == null ? null : (entry.getValue()).toString();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
} catch (IOException e) {
e.printStackTrace();
}
}
// 添加headers
addHeaders(httpPost, headers);
// 添加cookies
addCookies(httpPost, cookies);
HttpClientContext httpClientContext = new HttpClientContext();
CloseableHttpClient httpClient = getHttpClient();
try (CloseableHttpResponse response = httpClient.execute(httpPost, httpClientContext)) {
return getResEntity(response, false);
} finally {
if (!connectionPool.get()) {
httpClient.close();
}
}
}
/**
* post请求基础方法
*
* @param url
* @param headers
* @param parList
* @return cn.xanderye.util.HttpUtil.ResEntity
* @author XanderYe
* @date 2024/4/11
*/
public static ResEntity doPostPair(String url, Map<String, Object> headers, Map<String, Object> cookies, List<NameValuePair> parList) throws IOException {
HttpPost httpPost = new HttpPost(baseUrl + url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(parList, CHARSET));
} catch (IOException e) {
e.printStackTrace();
}
// 添加headers
addHeaders(httpPost, headers);
// 添加cookies
addCookies(httpPost, cookies);
HttpClientContext httpClientContext = new HttpClientContext();
CloseableHttpClient httpClient = getHttpClient();
try (CloseableHttpResponse response = httpClient.execute(httpPost, httpClientContext)) {
return getResEntity(response, false);
} finally {
if (!connectionPool.get()) {
httpClient.close();
}
}
}
/**
* POST提交JSON基础方法
*
* @param url
* @param headers
* @param json
* @return cn.xanderye.util.HttpUtil.ResEntity
* @author XanderYe
* @date 2020/2/4
*/
public static ResEntity doPostJSON(String url, Map<String, Object> headers, Map<String, Object> cookies, String json) throws IOException {
HttpPost httpPost = new HttpPost(baseUrl + url);
// 拼接参数
if (json != null && !"".equals(json)) {
StringEntity requestEntity = new StringEntity(json, CHARSET);
requestEntity.setContentEncoding(CHARSET);
requestEntity.setContentType("application/json");
httpPost.setEntity(requestEntity);
}
// 添加headers
addHeaders(httpPost, headers);
// 添加cookies
addCookies(httpPost, cookies);
HttpClientContext httpClientContext = new HttpClientContext();
CloseableHttpClient httpClient = getHttpClient();
try (CloseableHttpResponse response = httpClient.execute(httpPost, httpClientContext)) {
return getResEntity(response, false);
} finally {
if (!connectionPool.get()) {
httpClient.close();
}
}
}
/**
* POST提交XML基础方法
*
* @param url
* @param headers
* @param xml
* @return cn.xanderye.util.HttpUtil.ResEntity
* @author XanderYe
* @date 2020/2/4
*/
public static ResEntity doPostXML(String url, Map<String, Object> headers, Map<String, Object> cookies, String xml) throws IOException {
HttpPost httpPost = new HttpPost(baseUrl + url);
// 拼接参数
if (xml != null && !"".equals(xml)) {
StringEntity requestEntity = new StringEntity(xml, CHARSET);
requestEntity.setContentEncoding(CHARSET);
requestEntity.setContentType("application/xml");
httpPost.setEntity(requestEntity);
}
// 添加headers
addHeaders(httpPost, headers);
// 添加cookies
addCookies(httpPost, cookies);
HttpClientContext httpClientContext = new HttpClientContext();
CloseableHttpClient httpClient = getHttpClient();
try (CloseableHttpResponse response = httpClient.execute(httpPost, httpClientContext)) {
return getResEntity(response, false);
} finally {
if (!connectionPool.get()) {
httpClient.close();
}
}
}
/**
* get下载基础方法
*
* @param url
* @param headers
* @param cookies
* @param params
* @return cn.xanderye.util.HttpUtil.ResEntity
* @author XanderYe
* @date 2020/2/4
*/
public static ResEntity doDownload(String url, Map<String, Object> headers, Map<String, Object> cookies, Map<String, Object> params) throws IOException {
url = baseUrl + url;
// 拼接参数
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
String value = entry.getValue() == null ? null : (entry.getValue()).toString();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
try {
String parameters = EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET));
String symbol = url.contains("?") ? "&" : "?";
// 判断是否已带参数
url += symbol + parameters;
} catch (IOException e) {
e.printStackTrace();
}
}
HttpGet httpGet = new HttpGet(url);
// 添加headers
addHeaders(httpGet, headers);
// 添加cookies
addCookies(httpGet, cookies);
HttpClientContext httpClientContext = new HttpClientContext();
CloseableHttpClient httpClient = getHttpClient();
try (CloseableHttpResponse response = httpClient.execute(httpGet, httpClientContext)) {
return getResEntity(response, true);
} finally {
if (!connectionPool.get()) {
httpClient.close();
}
}
}
/**
* post上传基础方法,注意Content-Type
*
* @param url
* @param headers
* @param cookies
* @param bytes
* @return cn.xanderye.util.HttpUtil.ResEntity
* @author XanderYe
* @date 2020/2/4
*/
public static ResEntity doUpload(String url, Map<String, Object> headers, Map<String, Object> cookies, byte[] bytes) throws IOException {
HttpPost httpPost = new HttpPost(baseUrl + url);
// 拼接参数
if (bytes != null && bytes.length > 0) {
ByteArrayEntity requestEntity = new ByteArrayEntity(bytes);
httpPost.setEntity(requestEntity);
}
// 添加headers
addHeaders(httpPost, headers);
// 添加cookies
addCookies(httpPost, cookies);
HttpClientContext httpClientContext = new HttpClientContext();
CloseableHttpClient httpClient = getHttpClient();
try (CloseableHttpResponse response = httpClient.execute(httpPost, httpClientContext)) {
return getResEntity(response, false);
} finally {
if (!connectionPool.get()) {
httpClient.close();
}
}
}
/**
* 获取请求返回对象
* @param response
* @return cn.xanderye.util.HttpUtil.ResEntity
* @author XanderYe
* @date 2021/8/30
*/
private static ResEntity getResEntity(CloseableHttpResponse response, boolean binary) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
ResEntity resEntity = new ResEntity();
resEntity.setStatusCode(statusCode);
resEntity.setHeaders(getHeaders(response));
resEntity.setCookies(parseCookies(getCookieString(response)));
HttpEntity resultEntity = response.getEntity();
if (resultEntity != null) {
if (binary) {
byte[] bytes = EntityUtils.toByteArray(resultEntity);
resEntity.setBytes(bytes);
} else {
String res = EntityUtils.toString(resultEntity, CHARSET);
resEntity.setResponse(res);
}
EntityUtils.consume(resultEntity);
}
return resEntity;
}
/**
* 添加cookie
*
* @param httpRequestBase
* @return void
* @author XanderYe
* @date 2020-03-15
*/
private static void addHeaders(HttpRequestBase httpRequestBase, Map<String, Object> headers) {
// 设置默认UA
httpRequestBase.setHeader("User-Agent", DEFAULT_USER_AGENT);
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, Object> entry : headers.entrySet()) {
String key = entry.getKey();
String value = entry.getValue() == null ? "" : String.valueOf(entry.getValue());
httpRequestBase.setHeader(key, value);
}
}
}
/**
* 添加cookie
*
* @param cookies
* @return void
* @author XanderYe
* @date 2020-03-15
*/
private static void addCookies(HttpRequestBase httpRequestBase, Map<String, Object> cookies) {
if (cookies != null && !cookies.isEmpty()) {
StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry<String, Object> entry : cookies.entrySet()) {
String key = entry.getKey();
String value = entry.getValue() == null ? "" : String.valueOf(entry.getValue());
stringBuilder.append(key).append("=").append(value).append("; ");
}
httpRequestBase.addHeader("Cookie", stringBuilder.toString());
}
}
/**
* 从请求头中获取cookie字符串
* @param response
* @return java.lang.String
* @author XanderYe
* @date 2021/1/26
*/
private static String getCookieString(CloseableHttpResponse response) {
Header[] headers = response.getHeaders("Set-Cookie");
return Arrays.stream(headers).map(header -> {
String valueStr = header.getValue();
if (valueStr != null) {
String[] valueStrArray = valueStr.split(";");
if (valueStrArray.length > 0) {
return valueStrArray[0];
}
}
return valueStr;
}).collect(Collectors.joining("; "));
}
/**
* 获取请求头
* @param response
* @return java.util.Map<java.lang.String,java.lang.Object>
* @author XanderYe
* @date 2021/6/21
*/
private static Map<String, Object> getHeaders(CloseableHttpResponse response) {
Header[] headers = response.getAllHeaders();
Map<String, Object> headersMap = new HashMap<>();
for (Header header : headers) {
headersMap.put(header.getName(), header.getValue());
}
return headersMap;
}
/**
* 请求头转对象
*
* @param headerString
* @return java.util.Map<java.lang.String, java.lang.Object>
* @author XanderYe
* @date 2020/4/1
*/
public static Map<String, Object> parseHeaders(String headerString) {
Map<String, Object> headerMap = new HashMap<>(16);
if (headerString != null && !"".equals(headerString)) {
String[] headers = headerString.split(";");
if (headers.length > 0) {
for (String header : headers) {
int index = header.indexOf(":");
if (index > 0) {
String k = header.substring(0, index).trim();
String v = header.substring(index + 1).trim();
headerMap.put(k, v);
}
}
}
}
return headerMap;
}
/**
* 请求头转字符串
* @param headers
* @return java.lang.String
* @author XanderYe
* @date 2023/12/12
*/
public static String formatHeaders(Map<String, Object> headers) {
StringBuilder headerSb = new StringBuilder();
if (headers != null && !headers.isEmpty()) {
for (String key : headers.keySet()) {
Object valueObj = headers.get(key);
if (valueObj != null) {
headerSb.append(key).append(":").append(valueObj).append(";");
}
}
}
return headerSb.toString();
}
/**
* cookie转对象
*
* @param cookieString
* @return java.util.Map<java.lang.String, java.lang.Object>
* @author XanderYe
* @date 2020/4/1
*/
public static Map<String, Object> parseCookies(String cookieString) {
Map<String, Object> cookieMap = new HashMap<>(16);
if (cookieString != null && !"".equals(cookieString)) {
String[] cookies = cookieString.split(";");
if (cookies.length > 0) {
for (String parameter : cookies) {
int eqIndex = parameter.indexOf("=");
if (eqIndex > -1) {
String k = parameter.substring(0, eqIndex).trim();
String v = parameter.substring(eqIndex + 1).trim();
if (!"".equals(v)) {
cookieMap.put(k, v);
}
}
}
}
}
return cookieMap;
}
/**
* cookie转字符串
* @param cookies
* @return java.lang.String
* @author XanderYe
* @date 2023/12/12
*/
public static String formatCookies(Map<String, Object> cookies) {
StringBuilder cookieSb = new StringBuilder();
if (cookies != null && !cookies.isEmpty()) {
for (String key : cookies.keySet()) {
Object valueObj = cookies.get(key);
if (valueObj != null) {
cookieSb.append(key).append("=").append(valueObj).append(";");
}
}
}
return cookieSb.toString();
}
/**
* 请求参数转对象
*
* @param parameterString
* @return java.util.Map<java.lang.String, java.lang.Object>
* @author XanderYe
* @date 2020/4/1
*/
public static Map<String, Object> parseParameters(String parameterString) {
if (parameterString != null) {
String[] parameters = parameterString.split("&");
if (parameters.length > 0) {
Map<String, Object> paramMap = new HashMap<>(16);
for (String parameter : parameters) {
String[] value = parameter.split("=");
String k = value[0].trim();
String v = null;
if (value.length == 2) {
v = value[1].trim();
}
paramMap.put(k, v);
}
return paramMap;
}
}
return null;
}
/**
* 请求参数转字符串
* @param params
* @return java.lang.String
* @author XanderYe
* @date 2023/12/12
*/
public static String formatParameters(Map<String, Object> params) {
StringBuilder paramSb = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (String key : params.keySet()) {
Object valueObj = params.get(key);
if (valueObj != null) {
paramSb.append(key).append("=").append(valueObj).append("&");
}
}
}
if (paramSb.length() > 0) {
paramSb.deleteCharAt(paramSb.length() - 1);
}
return paramSb.toString();
}
/**
* 忽略证数配置
*
* @param
* @return org.apache.http.conn.ssl.SSLConnectionSocketFactory
* @author XanderYe
* @date 2020/2/14
*/
private static SSLConnectionSocketFactory ignoreCertificates() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
return new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" },
null, NoopHostnameVerifier.INSTANCE);
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
e.printStackTrace();
}
return null;
}
/**
* 重试配置
* @param
* @return org.apache.http.client.HttpRequestRetryHandler
* @author XanderYe
* @date 2021/6/24
*/
private static HttpRequestRetryHandler retryHandler() {
return (e, retryTimes, httpContext) -> {
if (retryTimes > retryCount) {
// 重试次数大于3次
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(httpContext);
HttpRequest request = clientContext.getRequest();
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// 如果请求被认为是幂等的,则重试
return true;
}
if (e instanceof NoHttpResponseException) {
// NoHttpResponseException异常重试
return true;
}
if (e instanceof ConnectTimeoutException) {
// 连接超时重试
return true;
}
if (e instanceof SocketTimeoutException) {
// 响应超时
return false;
}
if (e instanceof InterruptedIOException) {
// 超时
return false;
}
if (e instanceof UnknownHostException) {
// 未知主机
return false;
}
if (e instanceof SSLException) {
// SSL异常
return false;
}
return false;
};
}
/**
* 设置重定向
* @param customRedirect
* @return void
* @author XanderYe
* @date 2021/5/24
*/
public static void setRedirect(boolean customRedirect) {
redirect = customRedirect;
}
/**
* 配置代理
* @param customProxyIp
* @param customProxyPort
* @return void
* @author XanderYe
* @date 2021/5/24
*/
public static void setProxy(String customProxyIp, Integer customProxyPort) {
if (null != customProxyIp && !"".equals(customProxyIp) && null != customProxyPort) {
enableProxy = true;
proxyIp = customProxyIp;
proxyPort = customProxyPort;
}
}
/**
* 设置超时
* @param customConnectTimeout
* @param customSocketTimeout
* @return void
* @author XanderYe
* @date 2021/5/24
*/
public static void setTimeout(int customConnectTimeout, int customSocketTimeout) {
connectTimeout = customConnectTimeout;
socketTimeout = customSocketTimeout;
}
/**
* 设置重试机制
* @param customRetry
* @return void
* @author XanderYe
* @date 2021/6/24
*/
public static void setRetry(boolean retry, int customRetry) {
enableRetry = retry;
if (customRetry > 0) {
retryCount = customRetry;
}
}
/**
* 启用连接池
* @param customMaxTotal
* @param customMaxPerRoute
* @param customIdleTimeout
* @param customMonitorPeriod
* @return void
* @author XanderYe
* @date 2022/1/21
*/
public static void enableConnectionPool(int customMaxTotal, int customMaxPerRoute, int customIdleTimeout, int customMonitorPeriod) {
maxTotal = customMaxTotal;
maxPerRoute = customMaxPerRoute;
idleTimeout = customIdleTimeout;
monitorPeriod = customMonitorPeriod;
enableConnectionPool();
}