-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathHttpTask.java
More file actions
984 lines (897 loc) · 29.4 KB
/
HttpTask.java
File metadata and controls
984 lines (897 loc) · 29.4 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
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
package cn.zhxu.okhttps;
import cn.zhxu.data.ArrayListMap;
import cn.zhxu.data.ListMap;
import cn.zhxu.okhttps.HttpResult.State;
import cn.zhxu.okhttps.internal.*;
import cn.zhxu.okhttps.internal.AbstractHttpClient.TagTask;
import okhttp3.*;
import okhttp3.internal.http.HttpMethod;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* Created by 周旭(Troy.Zhou) on 2020/3/11.
*/
@SuppressWarnings("unchecked")
public abstract class HttpTask<C extends HttpTask<C>> implements Cancelable {
private static final String DOT = ".";
private static final String MULTIPART = "multipart/";
private static final String FORM = "x-www-form-urlencoded";
protected final AbstractHttpClient httpClient;
protected boolean nothrow;
protected boolean nextOnIO = false;
private final String urlPath;
private String tag;
private ListMap<String> headers;
private ListMap<Object> pathParams;
private ListMap<Object> urlParams;
private ListMap<Object> bodyParams;
private ListMap<FilePara> files;
private Object requestBody;
private String bodyType; // 都是小写形式
private String boundary; // MultipartBody 的 边界符
private Consumer<Process> onProcess;
private boolean processOnIO;
private long stepBytes = 0;
private double stepRate = -1;
private Object object;
private TagTask tagTask;
private Cancelable canceler;
private Charset charset;
protected boolean skipPreproc = false;
protected boolean skipSerialPreproc = false;
public HttpTask(AbstractHttpClient httpClient, String urlPath) {
this.httpClient = httpClient;
this.charset = httpClient.charset();
this.bodyType = httpClient.bodyType();
this.urlPath = urlPath;
}
/**
* 获取请求任务的URL地址
* @return URL地址
*/
public String getUrl() {
return urlPath;
}
/**
* @return 是否是 Websocket 通讯
*/
public boolean isWebsocket() {
return false;
}
/**
* @since 2.2.0
* @return 是否是 同步 Http 请求
*/
public boolean isSyncHttp() {
return false;
}
/**
* @since 2.2.0
* @return 是否是 异步 Http 请求
*/
public boolean isAsyncHttp() {
return false;
}
/**
* 获取请求任务的标签
* @return 标签
*/
public String getTag() {
return tag;
}
public String getBodyType() {
return bodyType;
}
/**
* 标签匹配
* 判断任务标签与指定的标签是否匹配(包含指定的标签)
* @param tag 标签
* @return 是否匹配
*/
public boolean isTagged(String tag) {
String theTag = this.tag;
if (theTag != null && tag != null) {
return theTag.equals(tag) || theTag.startsWith(tag + DOT) || theTag.endsWith(DOT + tag)
|| theTag.contains(DOT + tag + DOT);
}
return false;
}
/**
* 获取请求任务的头信息
* @return 头信息
*/
public ListMap<String> getHeaders() {
return headers;
}
/**
* @since 2.4.0
* @return 路径参数
*/
public ListMap<Object> getPathParas() {
return pathParams;
}
/**
* @since 2.4.0
* @return URL参数(查询参数)
*/
public ListMap<Object> getUrlParas() {
return urlParams;
}
/**
* @since 2.4.0
* @return 报文体参数
*/
public ListMap<Object> getBodyParas() {
return bodyParams;
}
/**
* @since 2.4.0
* @return 文件参数
*/
public ListMap<FilePara> getFileParas() {
return files;
}
/**
* @since 2.4.0
* @return 报文体
*/
public Object getRequestBody() {
return requestBody;
}
/**
* 获得被绑定的对象
* @return Object
*/
public Object getBound() {
return object;
}
/**
* 设置在发生异常时不向上抛出,设置后:
* 异步请求可以在异常回调内捕获异常,同步请求在返回结果中找到该异常
* @return HttpTask 实例
*/
public C nothrow() {
this.nothrow = true;
return (C) this;
}
/**
* 指定该请求跳过任何预处理器(包括串行和并行)
* @return HttpTask 实例
*/
public C skipPreproc() {
this.skipPreproc = true;
return (C) this;
}
/**
* 指定该请求跳过任何串行预处理器
* @return HttpTask 实例
*/
public C skipSerialPreproc() {
this.skipSerialPreproc = true;
return (C) this;
}
/**
* @since 2.0.0.RC
* 为请求任务添加标签
* @param tag 标签
* @return HttpTask 实例
*/
public C tag(String tag) {
if (tag != null) {
if (this.tag != null) {
this.tag = this.tag + DOT + tag;
} else {
this.tag = tag;
}
updateTagTask();
}
return (C) this;
}
/**
* @since 2.0.0
* 设置该请求的编码格式
* @param charset 编码格式
* @return HttpTask 实例
*/
public C charset(Charset charset) {
if (charset != null) {
this.charset = charset;
}
return (C) this;
}
/**
* @since 2.0.0
* 设置请求体的类型,如:form、json、xml、protobuf 等
* @param type 请求类型
* @return HttpTask 实例
*/
public C bodyType(String type) {
if (type != null) {
this.bodyType = type.toLowerCase();
}
return (C) this;
}
/**
* 下一个回调在IO线程执行
* @return HttpTask 实例
*/
public C nextOnIO() {
nextOnIO = true;
return (C) this;
}
/**
* 绑定一个对象
* @param object 对象
* @return HttpTask 实例
*/
public C bind(Object object) {
this.object = object;
return (C) this;
}
/**
* Basic Auth 认证
* @param username 用户名
* @param password 密码
* @return HttpTask 实例
* @since v3.5.0
*/
public C basicAuth(String username, String password) {
byte[] authData = (username + ':' + password).getBytes(StandardCharsets.UTF_8);
byte[] authBytes = Base64.getEncoder().encode(authData);
String authStr = new String(authBytes, StandardCharsets.UTF_8);
return addHeader("Authorization", "Basic " + authStr);
}
/**
* Bearer Auth 认证
* @param token 令牌
* @return HttpTask 实例
* @since v3.5.0
*/
public C bearerAuth(String token) {
return addHeader("Authorization", "Bearer " + token);
}
/**
* 添加请求头
* @param name 请求头名
* @param value 请求头值
* @return HttpTask 实例
*/
public C addHeader(String name, String value) {
if (name != null && value != null) {
if (headers == null) {
headers = new ArrayListMap<>();
}
headers.put(name, value);
}
return (C) this;
}
/**
* 添加请求头
* @param headers 请求头集合
* @return HttpTask 实例
*/
public C addHeader(Map<String, String> headers) {
if (headers != null) {
if (this.headers == null) {
this.headers = new ArrayListMap<>();
}
this.headers.putAll(headers);
}
return (C) this;
}
/**
* 设置Range头信息
* 表示接收报文体时跳过的字节数,用于断点续传
* @param rangeStart 表示从 rangeStart 个字节处开始接收,通常是已经下载的字节数,即上次的断点)
* @return HttpTask 实例
*/
public C setRange(long rangeStart) {
return addHeader("Range", "bytes=" + rangeStart + "-");
}
/**
* 设置 Range 头信息
* 设置接收报文体时接收的范围,用于分块下载
* @param rangeStart 表示从 rangeStart 个字节处开始接收
* @param rangeEnd 表示接收到 rangeEnd 个字节处
* @return HttpTask 实例
*/
public C setRange(long rangeStart, long rangeEnd) {
return addHeader("Range", "bytes=" + rangeStart + "-" + rangeEnd);
}
/**
* 设置报文体发送进度回调
* @param onProcess 进度回调函数
* @return HttpTask 实例
*/
public C setOnProcess(Consumer<Process> onProcess) {
this.onProcess = onProcess;
processOnIO = nextOnIO;
nextOnIO = false;
return (C) this;
}
/**
* 设置进度回调的步进字节,默认 8K(8192)
* 表示每接收 stepBytes 个字节,执行一次进度回调
* @param stepBytes 步进字节
* @return HttpTask 实例
*/
public C stepBytes(long stepBytes) {
this.stepBytes = stepBytes;
return (C) this;
}
/**
* 设置进度回调的步进比例
* 表示每接收 stepRate 比例,执行一次进度回调
* @param stepRate 步进比例
* @return HttpTask 实例
*/
public C stepRate(double stepRate) {
this.stepRate = stepRate;
return (C) this;
}
/**
* 路径参数:替换URL里的{name}
* @param name 参数名
* @param value 参数值
* @return HttpTask 实例
**/
public C addPathPara(String name, Object value) {
if (name != null && value != null) {
if (pathParams == null) {
pathParams = new ArrayListMap<>();
}
pathParams.put(name, value.toString());
}
return (C) this;
}
/**
* 路径参数:替换URL里的{name}
* @param params 参数集合
* @return HttpTask 实例
**/
public C addPathPara(Map<String, ?> params) {
if (pathParams == null) {
pathParams = new ArrayListMap<>();
}
if (params != null) {
pathParams.putAll(params);
}
return (C) this;
}
/**
* URL参数:拼接在URL后的参数
* @param name 参数名
* @param value 参数值
* @return HttpTask 实例
**/
public C addUrlPara(String name, Object value) {
if (name != null && value != null) {
if (urlParams == null) {
urlParams = new ArrayListMap<>();
}
urlParams.put(name, value.toString());
}
return (C) this;
}
/**
* URL参数:拼接在URL后的参数
* @param params 参数集合
* @return HttpTask 实例
**/
public C addUrlPara(Map<String, ?> params) {
if (urlParams == null) {
urlParams = new ArrayListMap<>();
}
if (params != null) {
urlParams.putAll(params);
}
return (C) this;
}
/**
* Body参数:放在Body里的参数
* @param name 参数名
* @param value 参数值
* @return HttpTask 实例
**/
public C addBodyPara(String name, Object value) {
if (name != null && value != null) {
if (bodyParams == null) {
bodyParams = new ArrayListMap<>();
}
bodyParams.put(name, value);
}
return (C) this;
}
/**
* Body参数:放在 Body 里的参数(该方法只适合表单提交方式)
* @param name 参数名
* @param type 媒体类型: 如 txt、json、xml 等,参考 {@link HTTP.Builder#getMediaTypes() }
* @param value 参数值
* @return HttpTask 实例
* @since v4.1.0
**/
public C addBodyPara(String name, String type, Object value) {
if (name != null && value != null) {
if (bodyParams == null) {
bodyParams = new ArrayListMap<>();
}
if (type == null) {
bodyParams.put(name, value);
} else {
bodyParams.put(name, new BodyPara(type, value));
}
}
return (C) this;
}
/**
* Body参数:放在Body里的参数
* @param params 参数集合
* @return HttpTask 实例
**/
public C addBodyPara(Map<String, ?> params) {
if (bodyParams == null) {
bodyParams = new ArrayListMap<>();
}
if (params != null) {
bodyParams.putAll(params);
}
return (C) this;
}
/**
* 设置 请求报文体
* @param body 请求报文体,可以是:
* <pre>
* byte[] - 字节数组(直接作为报文体) <br>
* String - 字符串(比如:JSON 字符串、键值对字符串,也是直接作为报文体)<br>
* POJO - 普通 Java 数据对象(由 {@link MsgConvertor } 来序列化) <br>
* InputStream - 输入流(v3.5.0 开始支持)
* </pre>
* @return HttpTask 实例
**/
public C setBodyPara(Object body) {
this.requestBody = body;
return (C) this;
}
/**
* 添加文件参数(以 multipart/form-data 形式上传)
* @param name 参数名
* @param filePath 文件路径
* @return HttpTask 实例
*/
public C addFilePara(String name, String filePath) {
return addFilePara(name, new File(filePath));
}
/**
* 添加文件参数(以 multipart/form-data 形式上传)
* @param name 参数名
* @param type 文件类型/扩展名: 如 txt、png、jpg、doc 等,参考 {@link HTTP.Builder#getMediaTypes() }
* @param filePath 文件路径
* @return HttpTask 实例
*/
public C addFilePara(String name, String type, String filePath) {
return addFilePara(name, type, new File(filePath));
}
/**
* 添加文件参数(以 multipart/form-data 形式上传)
* @param name 参数名
* @param file 文件
* @return HttpTask 实例
*/
public C addFilePara(String name, File file) {
if (file != null && file.exists()) {
String fileName = file.getName();
String type = fileName.substring(fileName.lastIndexOf(DOT) + 1);
return addFilePara(name, type, file);
}
return (C) this;
}
/**
* 添加文件参数(以 multipart/form-data 形式上传)
* @param name 参数名
* @param type 文件类型/扩展名: 如 txt、png、jpg、doc 等
* @param file 文件
* @return HttpTask 实例
*/
public C addFilePara(String name, String type, File file) {
if (name != null && file != null && file.exists()) {
if (files == null) {
files = new ArrayListMap<>();
}
files.put(name, new FilePara(type, file.getName(), file));
}
return (C) this;
}
/**
* 添加文件参数(以 multipart/form-data 形式上传)
* @param name 参数名
* @param type 文件类型/扩展名: 如 txt、png、jpg、doc 等
* @param content 文件内容
* @return HttpTask 实例
*/
public C addFilePara(String name, String type, byte[] content) {
return addFilePara(name, type, name + DOT + type, content);
}
/**
* 添加文件参数(以 multipart/form-data 形式上传)
* @param name 参数名
* @param content 文件内容
* @param fileName 文件名: 如 xxx.txt、xxx.png、xxx.doc 等
* @return HttpTask 实例
* @since v3.5.1
*/
public C addFilePara(String name, byte[] content, String fileName) {
if (fileName != null) {
int dotIdx = fileName.indexOf(DOT);
if (dotIdx >= 0 && dotIdx < fileName.length() - 1) {
String type = fileName.substring(dotIdx + 1);
return addFilePara(name, type, fileName, content);
}
return addFilePara(name, null, fileName, content);
}
return (C) this;
}
/**
* 添加文件参数(以 multipart/form-data 形式上传)
* @param name 参数名
* @param type 文件类型/扩展名: 如 txt、png、jpg、doc 等
* @param fileName 文件名
* @param content 文件内容
* @return HttpTask 实例
*/
public C addFilePara(String name, String type, String fileName, byte[] content) {
if (name != null && content != null) {
if (files == null) {
files = new ArrayListMap<>();
}
files.put(name, new FilePara(type, fileName, content));
}
return (C) this;
}
/**
* 添加文件参数(以 multipart/form-data 形式上传)
* @param name 参数名
* @param type 文件类型/扩展名: 如 txt、png、jpg、doc 等
* @param stream 文件输入流
* @return HttpTask 实例
* @since v3.5.0
*/
public C addFilePara(String name, String type, InputStream stream) {
return addFilePara(name, type, name + DOT + type, stream);
}
/**
* 添加文件参数(以 multipart/form-data 形式上传)
* @param name 参数名
* @param stream 文件输入流
* @param fileName 文件名: 如 xxx.txt、xxx.png、xxx.doc 等
* @return HttpTask 实例
* @since v3.5.1
*/
public C addFilePara(String name, InputStream stream, String fileName) {
if (fileName != null) {
int dotIdx = fileName.indexOf(DOT);
if (dotIdx >= 0 && dotIdx < fileName.length() - 1) {
String type = fileName.substring(dotIdx + 1);
return addFilePara(name, type, fileName, stream);
}
return addFilePara(name, null, fileName, stream);
}
return (C) this;
}
/**
* 添加文件参数(以 multipart/form-data 形式上传)
* @param name 参数名
* @param type 文件类型/扩展名: 如 txt、png、jpg、doc 等
* @param fileName 文件名
* @param stream 文件输入流
* @return HttpTask 实例
* @since v3.5.0
*/
public C addFilePara(String name, String type, String fileName, InputStream stream) {
if (name != null && stream != null) {
if (files == null) {
files = new ArrayListMap<>();
}
files.put(name, new FilePara(type, fileName, stream));
}
return (C) this;
}
/**
* @since v3.4.2
* @return MultipartBody 的边界符
*/
public String boundary() {
return boundary;
}
/**
* 设置 MultipartBody 的边界符
* @since v3.4.2
* @param boundary 边界符
* @return this
*/
public C boundary(String boundary) {
this.boundary = boundary;
return (C) this;
}
@Override
public boolean cancel() {
if (canceler != null) {
return canceler.cancel();
}
return false;
}
protected void registeTagTask(Cancelable canceler) {
if (tag != null && tagTask == null) {
tagTask = httpClient.addTagTask(tag, canceler, this);
}
this.canceler = canceler;
}
private void updateTagTask() {
if (tagTask != null) {
tagTask.setTag(tag);
} else
if (canceler != null) {
registeTagTask(canceler);
}
}
protected void removeTagTask() {
if (tag != null) {
httpClient.removeTagTask(this);
}
}
protected Call prepareCall(String method) {
Request request = prepareRequest(method.toUpperCase());
return httpClient.request(request);
}
protected Request prepareRequest(String method) {
boolean bodyCanUsed = HttpMethod.permitsRequestBody(method);
assertNotConflict(!bodyCanUsed);
Request.Builder builder = new Request.Builder()
.url(buildUrlPath());
buildHeaders(builder);
if (bodyCanUsed) {
RequestBody reqBody = buildRequestBody();
if (onProcess != null) {
long contentLength = contentLength(reqBody);
if (stepRate > 0 && stepRate <= 1) {
stepBytes = (long) (contentLength * stepRate);
}
if (stepBytes <= 0) {
stepBytes = Process.DEFAULT_STEP_BYTES;
}
reqBody = new ProcessRequestBody(reqBody, onProcess,
httpClient.executor().getExecutor(processOnIO),
contentLength, stepBytes);
} else {
reqBody = new FixedRequestBody(reqBody);
}
builder.method(method, reqBody);
} else {
builder.method(method, null);
}
if (tag != null) {
builder.tag(String.class, tag);
}
return builder.build();
}
private long contentLength(RequestBody reqBody) {
try {
return reqBody.contentLength();
} catch (IOException e) {
throw new OkHttpsException("无法获取请求体长度", e);
}
}
private void buildHeaders(Request.Builder builder) {
if (headers != null) {
headers.forEach((name, value) -> {
if (value == null) return;
builder.addHeader(name, value);
});
}
}
protected State toState(IOException e) {
if (e instanceof SocketTimeoutException) {
return State.TIMEOUT;
} else if (e instanceof UnknownHostException || e instanceof ConnectException) {
return State.NETWORK_ERROR;
}
String msg = e.getMessage();
if (msg != null && ("Canceled".equals(msg) || e instanceof SocketException
&& (msg.startsWith("Socket operation on nonsocket") || "Socket closed".equals(msg)))) {
return State.CANCELED;
}
return State.EXCEPTION;
}
private RequestBody buildRequestBody() {
if (bodyParams != null && (OkHttps.FORM_DATA.equals(bodyType) || bodyType.startsWith(MULTIPART))
|| files != null) {
MultipartBody.Builder builder = multipartBodyBuilder();
if (bodyParams != null) {
bodyParams.forEach((key, value) -> {
if (value == null) return;
MediaType contentType = null;
String bodyValue;
if (value instanceof BodyPara) {
BodyPara para = (BodyPara) value;
contentType = httpClient.mediaType(para.getType());
bodyValue = para.getValue().toString();
} else {
bodyValue = value.toString();
}
byte[] content = bodyValue.getBytes(charset);
RequestBody body = RequestBody.create(contentType, content);
builder.addPart(MultipartBody.Part.createFormData(key, null, body));
});
}
if (files != null) {
files.forEach((name, file) -> {
MediaType type = httpClient.mediaType(file.getType());
builder.addFormDataPart(
name,
file.getFileName(),
file.toRequestBody(type)
);
});
}
return builder.build();
}
if (requestBody != null) {
return toRequestBody(requestBody);
}
if (bodyParams == null) {
return emptyRequestBody();
}
if (OkHttps.FORM.equals(bodyType) || bodyType.endsWith(FORM)) {
FormBody.Builder builder = new FormBody.Builder(charset);
bodyParams.forEach((key, value) -> {
if (value == null) return;
builder.add(key, value.toString());
});
return builder.build();
}
return toRequestBody(bodyParams);
}
private MultipartBody.Builder multipartBodyBuilder() {
MultipartBody.Builder builder;
if (boundary != null) {
builder = new MultipartBody.Builder(boundary);
} else {
builder = new MultipartBody.Builder();
}
if (bodyType.startsWith(MULTIPART)) {
try {
builder.setType(MediaType.get(bodyType));
} catch (IllegalArgumentException ignore) { }
} else {
builder.setType(MultipartBody.FORM);
}
return builder;
}
private RequestBody emptyRequestBody() {
if (OkHttps.FORM_DATA.equalsIgnoreCase(bodyType)) {
return new MultipartBody.Builder().setType(MultipartBody.FORM).build();
}
return RequestBody.create(mediaType(), new byte[]{});
}
private MediaType mediaType() {
return httpClient.executor().doMsgConvert(bodyType, null).mediaType(charset);
}
private RequestBody toRequestBody(Object bodyObj) {
if (bodyObj instanceof byte[] || bodyObj instanceof String) {
byte[] body = bodyObj instanceof byte[] ? (byte[]) bodyObj : ((String) bodyObj).getBytes(charset);
return RequestBody.create(mediaType(), body);
}
if (bodyObj instanceof InputStream) {
return new StreamRequestBody(mediaType(), (InputStream) bodyObj);
}
TaskExecutor.Data<byte[]> data = httpClient.executor().doMsgConvert(bodyType, c -> c.serialize(bodyObj, charset));
return RequestBody.create(data.mediaType(charset), data.data);
}
private String buildUrlPath() {
if (Platform.isBlank(urlPath)) {
throw new OkHttpsException("url 不能为空!");
}
StringBuilder sb = new StringBuilder(urlPath);
if (pathParams != null) {
pathParams.forEach((name, value) -> {
String target = "{" + name + "}";
int start = sb.indexOf(target);
if (start >= 0) {
String newValue = value != null ? value.toString() : "";
sb.replace(start, start + target.length(), newValue);
} else {
throw new OkHttpsException("PathPara [ " + name + " ] 不存在于 url [ " + urlPath + " ]");
}
});
}
if (urlParams != null) {
if (sb.indexOf("?") >= 0) { // contains("?")
int lastIndex = sb.length() - 1;
if (sb.lastIndexOf("?") < lastIndex) { // !endsWith("?")
if (sb.lastIndexOf("=") < sb.lastIndexOf("?") + 2) {
throw new OkHttpsException("url 格式错误,'?' 后没有发现 '='");
}
if (sb.lastIndexOf("&") < lastIndex) { // !endsWith("&")
sb.append('&');
}
}
} else {
sb.append('?');
}
urlParams.forEach((name, value) -> {
if (value == null) return;
sb.append(name).append('=').append(value).append('&');
});
sb.delete(sb.length() - 1, sb.length());
}
return sb.toString();
}
/**
* 参数冲突校验
* @param bodyCantUsed 报文体是否不可用
*/
protected void assertNotConflict(boolean bodyCantUsed) {
if (bodyCantUsed) {
if (requestBody != null) {
throw new OkHttpsException("GET | HEAD request can not call setBodyPara(..) method!");
}
if (isNotEmpty(bodyParams)) {
throw new OkHttpsException("GET | HEAD request can not call addBodyPara(..) method!");
}
if (isNotEmpty(files)) {
throw new OkHttpsException("GET | HEAD request can not call addFilePara(..) method!");
}
}
if (requestBody != null) {
if (isNotEmpty(bodyParams)) {
throw new OkHttpsException("can not call addBodyPara(..) and setBodyPara(..) at the same time!");
}
if (isNotEmpty(files)) {
throw new OkHttpsException("can not call addFilePara(..) and setBodyPara(..) at the same time!");
}
}
}
private static boolean isNotEmpty(Map<String, ?> map) {
return map != null && !map.isEmpty();
}
/**
* @param latch CountDownLatch
* @return true 表示已超时:false 表示未超时
*/
protected boolean timeoutAwait(CountDownLatch latch) {
try {
return !latch.await(httpClient.preprocTimeoutMillis(),
TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new OkHttpsException("execute timeout: " + urlPath, e);
}
}
protected HttpResult timeoutResult() {
if (nothrow) {
return new RealHttpResult(this, State.TIMEOUT);
}
throw new OkHttpsException(State.TIMEOUT, "execute timeout: " + urlPath);
}
public Charset charset(Response response) {
ResponseBody b = response.body();
MediaType type = b != null ? b.contentType() : null;
return type != null ? type.charset(charset) : charset;
}
protected void execute(Runnable command, boolean onIo) {
httpClient.executor().execute(command, onIo);
}
public AbstractHttpClient httpClient() {
return httpClient;
}
}