-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
HttpConnection.java
1415 lines (1232 loc) · 50.1 KB
/
HttpConnection.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 org.jsoup.helper;
import org.jsoup.Connection;
import org.jsoup.HttpStatusException;
import org.jsoup.UncheckedIOException;
import org.jsoup.UnsupportedMimeTypeException;
import org.jsoup.internal.ControllableInputStream;
import org.jsoup.internal.Functions;
import org.jsoup.internal.SharedConstants;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
import org.jsoup.parser.StreamParser;
import org.jsoup.parser.TokenQueue;
import org.jspecify.annotations.Nullable;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.CookieManager;
import java.net.CookieStore;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import static org.jsoup.Connection.Method.HEAD;
import static org.jsoup.helper.DataUtil.UTF_8;
import static org.jsoup.internal.Normalizer.lowerCase;
/**
* Implementation of {@link Connection}.
* @see org.jsoup.Jsoup#connect(String)
*/
@SuppressWarnings("CharsetObjectCanBeUsed")
public class HttpConnection implements Connection {
public static final String CONTENT_ENCODING = "Content-Encoding";
/**
* Many users would get caught by not setting a user-agent and therefore getting different responses on their desktop
* vs in jsoup, which would otherwise default to {@code Java}. So by default, use a desktop UA.
*/
public static final String DEFAULT_UA =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36";
private static final String USER_AGENT = "User-Agent";
public static final String CONTENT_TYPE = "Content-Type";
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
public static final String FORM_URL_ENCODED = "application/x-www-form-urlencoded";
private static final int HTTP_TEMP_REDIR = 307; // http/1.1 temporary redirect, not in Java's set.
private static final String DefaultUploadType = "application/octet-stream";
private static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
/**
Create a new Connection, with the request URL specified.
@param url the URL to fetch from
@return a new Connection object
*/
public static Connection connect(String url) {
Connection con = new HttpConnection();
con.url(url);
return con;
}
/**
Create a new Connection, with the request URL specified.
@param url the URL to fetch from
@return a new Connection object
*/
public static Connection connect(URL url) {
Connection con = new HttpConnection();
con.url(url);
return con;
}
/**
Create a new, empty HttpConnection.
*/
public HttpConnection() {
req = new Request();
}
/**
Create a new Request by deep-copying an existing Request. Note that the data and body of the original are not
copied. All other settings (proxy, parser, cookies, etc) are copied.
@param copy the request to copy
*/
HttpConnection(Request copy) {
req = new Request(copy);
}
private static String encodeMimeName(String val) {
return val.replace("\"", "%22");
}
private HttpConnection.Request req;
private Connection.@Nullable Response res;
@Override
public Connection newRequest() {
// copy the prototype request for the different settings, cookie manager, etc
return new HttpConnection(req);
}
/** Create a new Connection that just wraps the provided Request and Response */
private HttpConnection(Request req, Response res) {
this.req = req;
this.res = res;
}
@Override
public Connection url(URL url) {
req.url(url);
return this;
}
@Override
public Connection url(String url) {
Validate.notEmptyParam(url, "url");
try {
req.url(new URL(url));
} catch (MalformedURLException e) {
throw new IllegalArgumentException(String.format("The supplied URL, '%s', is malformed. Make sure it is an absolute URL, and starts with 'http://' or 'https://'. See https://jsoup.org/cookbook/extracting-data/working-with-urls", url), e);
}
return this;
}
@Override
public Connection proxy(@Nullable Proxy proxy) {
req.proxy(proxy);
return this;
}
@Override
public Connection proxy(String host, int port) {
req.proxy(host, port);
return this;
}
@Override
public Connection userAgent(String userAgent) {
Validate.notNullParam(userAgent, "userAgent");
req.header(USER_AGENT, userAgent);
return this;
}
@Override
public Connection timeout(int millis) {
req.timeout(millis);
return this;
}
@Override
public Connection maxBodySize(int bytes) {
req.maxBodySize(bytes);
return this;
}
@Override
public Connection followRedirects(boolean followRedirects) {
req.followRedirects(followRedirects);
return this;
}
@Override
public Connection referrer(String referrer) {
Validate.notNullParam(referrer, "referrer");
req.header("Referer", referrer);
return this;
}
@Override
public Connection method(Method method) {
req.method(method);
return this;
}
@Override
public Connection ignoreHttpErrors(boolean ignoreHttpErrors) {
req.ignoreHttpErrors(ignoreHttpErrors);
return this;
}
@Override
public Connection ignoreContentType(boolean ignoreContentType) {
req.ignoreContentType(ignoreContentType);
return this;
}
@Override
public Connection data(String key, String value) {
req.data(KeyVal.create(key, value));
return this;
}
@Override
public Connection sslSocketFactory(SSLSocketFactory sslSocketFactory) {
req.sslSocketFactory(sslSocketFactory);
return this;
}
@Override
public Connection data(String key, String filename, InputStream inputStream) {
req.data(KeyVal.create(key, filename, inputStream));
return this;
}
@Override
public Connection data(String key, String filename, InputStream inputStream, String contentType) {
req.data(KeyVal.create(key, filename, inputStream).contentType(contentType));
return this;
}
@Override
public Connection data(Map<String, String> data) {
Validate.notNullParam(data, "data");
for (Map.Entry<String, String> entry : data.entrySet()) {
req.data(KeyVal.create(entry.getKey(), entry.getValue()));
}
return this;
}
@Override
public Connection data(String... keyvals) {
Validate.notNullParam(keyvals, "keyvals");
Validate.isTrue(keyvals.length %2 == 0, "Must supply an even number of key value pairs");
for (int i = 0; i < keyvals.length; i += 2) {
String key = keyvals[i];
String value = keyvals[i+1];
Validate.notEmpty(key, "Data key must not be empty");
Validate.notNull(value, "Data value must not be null");
req.data(KeyVal.create(key, value));
}
return this;
}
@Override
public Connection data(Collection<Connection.KeyVal> data) {
Validate.notNullParam(data, "data");
for (Connection.KeyVal entry: data) {
req.data(entry);
}
return this;
}
@Override
public Connection.KeyVal data(String key) {
Validate.notEmptyParam(key, "key");
for (Connection.KeyVal keyVal : request().data()) {
if (keyVal.key().equals(key))
return keyVal;
}
return null;
}
@Override
public Connection requestBody(String body) {
req.requestBody(body);
return this;
}
@Override
public Connection header(String name, String value) {
req.header(name, value);
return this;
}
@Override
public Connection headers(Map<String,String> headers) {
Validate.notNullParam(headers, "headers");
for (Map.Entry<String,String> entry : headers.entrySet()) {
req.header(entry.getKey(),entry.getValue());
}
return this;
}
@Override
public Connection cookie(String name, String value) {
req.cookie(name, value);
return this;
}
@Override
public Connection cookies(Map<String, String> cookies) {
Validate.notNullParam(cookies, "cookies");
for (Map.Entry<String, String> entry : cookies.entrySet()) {
req.cookie(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public Connection cookieStore(CookieStore cookieStore) {
// create a new cookie manager using the new store
req.cookieManager = new CookieManager(cookieStore, null);
return this;
}
@Override
public CookieStore cookieStore() {
return req.cookieManager.getCookieStore();
}
@Override
public Connection parser(Parser parser) {
req.parser(parser);
return this;
}
@Override
public Document get() throws IOException {
req.method(Method.GET);
execute();
Validate.notNull(res);
return res.parse();
}
@Override
public Document post() throws IOException {
req.method(Method.POST);
execute();
Validate.notNull(res);
return res.parse();
}
@Override
public Connection.Response execute() throws IOException {
res = Response.execute(req);
return res;
}
@Override
public Connection.Request request() {
return req;
}
@Override
public Connection request(Connection.Request request) {
req = (HttpConnection.Request) request; // will throw a class-cast exception if the user has extended some but not all of Connection; that's desired
return this;
}
@Override
public Connection.Response response() {
if (res == null) {
throw new IllegalArgumentException("You must execute the request before getting a response.");
}
return res;
}
@Override
public Connection response(Connection.Response response) {
res = response;
return this;
}
@Override
public Connection postDataCharset(String charset) {
req.postDataCharset(charset);
return this;
}
@Override public Connection auth(RequestAuthenticator authenticator) {
req.auth(authenticator);
return this;
}
@SuppressWarnings("unchecked")
private static abstract class Base<T extends Connection.Base<T>> implements Connection.Base<T> {
private static final URL UnsetUrl; // only used if you created a new Request()
static {
try {
UnsetUrl = new URL("http://undefined/");
} catch (MalformedURLException e) {
throw new IllegalStateException(e);
}
}
URL url = UnsetUrl;
Method method = Method.GET;
Map<String, List<String>> headers;
Map<String, String> cookies;
private Base() {
headers = new LinkedHashMap<>();
cookies = new LinkedHashMap<>();
}
private Base(Base<T> copy) {
url = copy.url; // unmodifiable object
method = copy.method;
headers = new LinkedHashMap<>();
for (Map.Entry<String, List<String>> entry : copy.headers.entrySet()) {
headers.put(entry.getKey(), new ArrayList<>(entry.getValue()));
}
cookies = new LinkedHashMap<>(); cookies.putAll(copy.cookies); // just holds strings
}
@Override
public URL url() {
if (url == UnsetUrl)
throw new IllegalArgumentException("URL not set. Make sure to call #url(...) before executing the request.");
return url;
}
@Override
public T url(URL url) {
Validate.notNullParam(url, "url");
this.url = new UrlBuilder(url).build();
return (T) this;
}
@Override
public Method method() {
return method;
}
@Override
public T method(Method method) {
Validate.notNullParam(method, "method");
this.method = method;
return (T) this;
}
@Override
public String header(String name) {
Validate.notNullParam(name, "name");
List<String> vals = getHeadersCaseInsensitive(name);
if (vals.size() > 0) {
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
return StringUtil.join(vals, ", ");
}
return null;
}
@Override
public T addHeader(String name, @Nullable String value) {
Validate.notEmptyParam(name, "name");
//noinspection ConstantConditions
value = value == null ? "" : value;
List<String> values = headers(name);
if (values.isEmpty()) {
values = new ArrayList<>();
headers.put(name, values);
}
values.add(value);
return (T) this;
}
@Override
public List<String> headers(String name) {
Validate.notEmptyParam(name, "name");
return getHeadersCaseInsensitive(name);
}
@Override
public T header(String name, String value) {
Validate.notEmptyParam(name, "name");
removeHeader(name); // ensures we don't get an "accept-encoding" and a "Accept-Encoding"
addHeader(name, value);
return (T) this;
}
@Override
public boolean hasHeader(String name) {
Validate.notEmptyParam(name, "name");
return !getHeadersCaseInsensitive(name).isEmpty();
}
/**
* Test if the request has a header with this value (case insensitive).
*/
@Override
public boolean hasHeaderWithValue(String name, String value) {
Validate.notEmpty(name);
Validate.notEmpty(value);
List<String> values = headers(name);
for (String candidate : values) {
if (value.equalsIgnoreCase(candidate))
return true;
}
return false;
}
@Override
public T removeHeader(String name) {
Validate.notEmptyParam(name, "name");
Map.Entry<String, List<String>> entry = scanHeaders(name); // remove is case-insensitive too
if (entry != null)
headers.remove(entry.getKey()); // ensures correct case
return (T) this;
}
@Override
public Map<String, String> headers() {
LinkedHashMap<String, String> map = new LinkedHashMap<>(headers.size());
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String header = entry.getKey();
List<String> values = entry.getValue();
if (values.size() > 0)
map.put(header, values.get(0));
}
return map;
}
@Override
public Map<String, List<String>> multiHeaders() {
return headers;
}
private List<String> getHeadersCaseInsensitive(String name) {
Validate.notNull(name);
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
if (name.equalsIgnoreCase(entry.getKey()))
return entry.getValue();
}
return Collections.emptyList();
}
private Map.@Nullable Entry<String, List<String>> scanHeaders(String name) {
String lc = lowerCase(name);
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
if (lowerCase(entry.getKey()).equals(lc))
return entry;
}
return null;
}
@Override
public String cookie(String name) {
Validate.notEmptyParam(name, "name");
return cookies.get(name);
}
@Override
public T cookie(String name, String value) {
Validate.notEmptyParam(name, "name");
Validate.notNullParam(value, "value");
cookies.put(name, value);
return (T) this;
}
@Override
public boolean hasCookie(String name) {
Validate.notEmptyParam(name, "name");
return cookies.containsKey(name);
}
@Override
public T removeCookie(String name) {
Validate.notEmptyParam(name, "name");
cookies.remove(name);
return (T) this;
}
@Override
public Map<String, String> cookies() {
return cookies;
}
}
public static class Request extends HttpConnection.Base<Connection.Request> implements Connection.Request {
static {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
// make sure that we can send Sec-Fetch-Site headers etc.
}
private @Nullable Proxy proxy;
private int timeoutMilliseconds;
private int maxBodySizeBytes;
private boolean followRedirects;
private final Collection<Connection.KeyVal> data;
private @Nullable String body = null;
private boolean ignoreHttpErrors = false;
private boolean ignoreContentType = false;
private Parser parser;
private boolean parserDefined = false; // called parser(...) vs initialized in ctor
private String postDataCharset = DataUtil.defaultCharsetName;
private @Nullable SSLSocketFactory sslSocketFactory;
private CookieManager cookieManager;
private @Nullable RequestAuthenticator authenticator;
private volatile boolean executing = false;
Request() {
super();
timeoutMilliseconds = 30000; // 30 seconds
maxBodySizeBytes = 1024 * 1024 * 2; // 2MB
followRedirects = true;
data = new ArrayList<>();
method = Method.GET;
addHeader("Accept-Encoding", "gzip");
addHeader(USER_AGENT, DEFAULT_UA);
parser = Parser.htmlParser();
cookieManager = new CookieManager(); // creates a default InMemoryCookieStore
}
Request(Request copy) {
super(copy);
proxy = copy.proxy;
postDataCharset = copy.postDataCharset;
timeoutMilliseconds = copy.timeoutMilliseconds;
maxBodySizeBytes = copy.maxBodySizeBytes;
followRedirects = copy.followRedirects;
data = new ArrayList<>(); // data not copied
//body not copied
ignoreHttpErrors = copy.ignoreHttpErrors;
ignoreContentType = copy.ignoreContentType;
parser = copy.parser.newInstance(); // parsers and their tree-builders maintain state, so need a fresh copy
parserDefined = copy.parserDefined;
sslSocketFactory = copy.sslSocketFactory; // these are all synchronized so safe to share
cookieManager = copy.cookieManager;
authenticator = copy.authenticator;
executing = false;
}
@Override
public Proxy proxy() {
return proxy;
}
@Override
public Request proxy(@Nullable Proxy proxy) {
this.proxy = proxy;
return this;
}
@Override
public Request proxy(String host, int port) {
this.proxy = new Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(host, port));
return this;
}
@Override
public int timeout() {
return timeoutMilliseconds;
}
@Override
public Request timeout(int millis) {
Validate.isTrue(millis >= 0, "Timeout milliseconds must be 0 (infinite) or greater");
timeoutMilliseconds = millis;
return this;
}
@Override
public int maxBodySize() {
return maxBodySizeBytes;
}
@Override
public Connection.Request maxBodySize(int bytes) {
Validate.isTrue(bytes >= 0, "maxSize must be 0 (unlimited) or larger");
maxBodySizeBytes = bytes;
return this;
}
@Override
public boolean followRedirects() {
return followRedirects;
}
@Override
public Connection.Request followRedirects(boolean followRedirects) {
this.followRedirects = followRedirects;
return this;
}
@Override
public boolean ignoreHttpErrors() {
return ignoreHttpErrors;
}
@Override
public SSLSocketFactory sslSocketFactory() {
return sslSocketFactory;
}
@Override
public void sslSocketFactory(SSLSocketFactory sslSocketFactory) {
this.sslSocketFactory = sslSocketFactory;
}
@Override
public Connection.Request ignoreHttpErrors(boolean ignoreHttpErrors) {
this.ignoreHttpErrors = ignoreHttpErrors;
return this;
}
@Override
public boolean ignoreContentType() {
return ignoreContentType;
}
@Override
public Connection.Request ignoreContentType(boolean ignoreContentType) {
this.ignoreContentType = ignoreContentType;
return this;
}
@Override
public Request data(Connection.KeyVal keyval) {
Validate.notNullParam(keyval, "keyval");
data.add(keyval);
return this;
}
@Override
public Collection<Connection.KeyVal> data() {
return data;
}
@Override
public Connection.Request requestBody(@Nullable String body) {
this.body = body;
return this;
}
@Override
public String requestBody() {
return body;
}
@Override
public Request parser(Parser parser) {
this.parser = parser;
parserDefined = true;
return this;
}
@Override
public Parser parser() {
return parser;
}
@Override
public Connection.Request postDataCharset(String charset) {
Validate.notNullParam(charset, "charset");
if (!Charset.isSupported(charset)) throw new IllegalCharsetNameException(charset);
this.postDataCharset = charset;
return this;
}
@Override
public String postDataCharset() {
return postDataCharset;
}
CookieManager cookieManager() {
return cookieManager;
}
@Override public Connection.Request auth(@Nullable RequestAuthenticator authenticator) {
this.authenticator = authenticator;
return this;
}
@Override @Nullable public RequestAuthenticator auth() {
return authenticator;
}
}
public static class Response extends HttpConnection.Base<Connection.Response> implements Connection.Response {
private static final int MAX_REDIRECTS = 20;
private static final String LOCATION = "Location";
private final int statusCode;
private final String statusMessage;
private @Nullable ByteBuffer byteData;
private @Nullable ControllableInputStream bodyStream;
private @Nullable HttpURLConnection conn;
private @Nullable String charset;
private @Nullable final String contentType;
private boolean executed = false;
private boolean inputStreamRead = false;
private int numRedirects = 0;
private final HttpConnection.Request req;
/*
* Matches XML content types (like text/xml, image/svg+xml, application/xhtml+xml;charset=UTF8, etc)
*/
private static final Pattern xmlContentTypeRxp = Pattern.compile("(\\w+)/\\w*\\+?xml.*");
/**
<b>Internal only! </b>Creates a dummy HttpConnection.Response, useful for testing. All actual responses
are created from the HttpURLConnection and fields defined.
*/
Response() {
super();
statusCode = 400;
statusMessage = "Request not made";
req = new Request();
contentType = null;
}
static Response execute(HttpConnection.Request req) throws IOException {
return execute(req, null);
}
static Response execute(HttpConnection.Request req, @Nullable Response previousResponse) throws IOException {
synchronized (req) {
Validate.isFalse(req.executing, "Multiple threads were detected trying to execute the same request concurrently. Make sure to use Connection#newRequest() and do not share an executing request between threads.");
req.executing = true;
}
Validate.notNullParam(req, "req");
URL url = req.url();
Validate.notNull(url, "URL must be specified to connect");
String protocol = url.getProtocol();
if (!protocol.equals("http") && !protocol.equals("https"))
throw new MalformedURLException("Only http & https protocols supported");
final boolean methodHasBody = req.method().hasBody();
final boolean hasRequestBody = req.requestBody() != null;
if (!methodHasBody)
Validate.isFalse(hasRequestBody, "Cannot set a request body for HTTP method " + req.method());
// set up the request for execution
String mimeBoundary = null;
if (req.data().size() > 0 && (!methodHasBody || hasRequestBody))
serialiseRequestUrl(req);
else if (methodHasBody)
mimeBoundary = setOutputContentType(req);
long startTime = System.nanoTime();
HttpURLConnection conn = createConnection(req);
Response res = null;
try {
conn.connect();
if (conn.getDoOutput()) {
OutputStream out = conn.getOutputStream();
try { writePost(req, out, mimeBoundary); }
catch (IOException e) { conn.disconnect(); throw e; }
finally { out.close(); }
}
int status = conn.getResponseCode();
res = new Response(conn, req, previousResponse);
// redirect if there's a location header (from 3xx, or 201 etc)
if (res.hasHeader(LOCATION) && req.followRedirects()) {
if (status != HTTP_TEMP_REDIR) {
req.method(Method.GET); // always redirect with a get. any data param from original req are dropped.
req.data().clear();
req.requestBody(null);
req.removeHeader(CONTENT_TYPE);
}
String location = res.header(LOCATION);
Validate.notNull(location);
if (location.startsWith("http:/") && location.charAt(6) != '/') // fix broken Location: http:/temp/AAG_New/en/index.php
location = location.substring(6);
URL redir = StringUtil.resolve(req.url(), location);
req.url(redir);
req.executing = false;
return execute(req, res);
}
if ((status < 200 || status >= 400) && !req.ignoreHttpErrors())
throw new HttpStatusException("HTTP error fetching URL", status, req.url().toString());
// check that we can handle the returned content type; if not, abort before fetching it
String contentType = res.contentType();
if (contentType != null
&& !req.ignoreContentType()
&& !contentType.startsWith("text/")
&& !xmlContentTypeRxp.matcher(contentType).matches()
)
throw new UnsupportedMimeTypeException("Unhandled content type. Must be text/*, */xml, or */*+xml",
contentType, req.url().toString());
// switch to the XML parser if content type is xml and not parser not explicitly set
if (contentType != null && xmlContentTypeRxp.matcher(contentType).matches()) {
if (!req.parserDefined) req.parser(Parser.xmlParser());
}
res.charset = DataUtil.getCharsetFromContentType(res.contentType); // may be null, readInputStream deals with it
if (conn.getContentLength() != 0 && req.method() != HEAD) { // -1 means unknown, chunked. sun throws an IO exception on 500 response with no content when trying to read body
InputStream stream = conn.getErrorStream() != null ? conn.getErrorStream() : conn.getInputStream();
if (res.hasHeaderWithValue(CONTENT_ENCODING, "gzip"))
stream = new GZIPInputStream(stream);
else if (res.hasHeaderWithValue(CONTENT_ENCODING, "deflate"))
stream = new InflaterInputStream(stream, new Inflater(true));
res.bodyStream = ControllableInputStream.wrap(
stream, SharedConstants.DefaultBufferSize, req.maxBodySize())
.timeout(startTime, req.timeout());
} else {
res.byteData = DataUtil.emptyByteBuffer();
}
} catch (IOException e) {
if (res != null) res.safeClose(); // will be non-null if got to conn
throw e;
} finally {
req.executing = false;
// detach any thread local auth delegate
if (req.authenticator != null)
AuthenticationHandler.handler.remove();
}
res.executed = true;
return res;
}
@Override
public int statusCode() {
return statusCode;
}
@Override
public String statusMessage() {
return statusMessage;
}
@Override
public String charset() {
return charset;
}
@Override
public Response charset(String charset) {
this.charset = charset;
return this;
}
@Override
public String contentType() {
return contentType;
}
/** Called from parse() or streamParser(), validates and prepares the input stream, and aligns common settings. */
private InputStream prepareParse() {
Validate.isTrue(executed, "Request must be executed (with .execute(), .get(), or .post() before parsing response");
InputStream stream = bodyStream;
if (byteData != null) { // bytes have been read in to the buffer, parse that
stream = new ByteArrayInputStream(byteData.array());
inputStreamRead = false; // ok to reparse if in bytes
}
Validate.isFalse(inputStreamRead, "Input stream already read and parsed, cannot re-read.");
Validate.notNull(stream);
inputStreamRead = true;
return stream;
}
@Override public Document parse() throws IOException {
InputStream stream = prepareParse();
Document doc = DataUtil.parseInputStream(stream, charset, url.toExternalForm(), req.parser());
doc.connection(new HttpConnection(req, this)); // because we're static, don't have the connection obj. // todo - maybe hold in the req?
charset = doc.outputSettings().charset().name(); // update charset from meta-equiv, possibly
safeClose();
return doc;
}
@Override public StreamParser streamParser() throws IOException {
InputStream stream = prepareParse();
String baseUri = url.toExternalForm();
DataUtil.CharsetDoc charsetDoc = DataUtil.detectCharset(stream, charset, baseUri, req.parser());
// note that there may be a document in CharsetDoc as a result of scanning meta-data -- but as requires a stream parse, it is not used here. todo - revisit.
// set up the stream parser and rig this connection up to the parsed doc:
StreamParser streamer = new StreamParser(req.parser());
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charsetDoc.charset));
DataUtil.maybeSkipBom(reader, charsetDoc);
streamer.parse(reader, baseUri); // initializes the parse and the document, but does not step() it
streamer.document().connection(new HttpConnection(req, this));
charset = charsetDoc.charset.name();
// we don't safeClose() as in parse(); caller must close streamParser to close InputStream stream
return streamer;
}
private void prepareByteData() {
Validate.isTrue(executed, "Request must be executed (with .execute(), .get(), or .post() before getting response body");
if (bodyStream != null && byteData == null) {
Validate.isFalse(inputStreamRead, "Request has already been read (with .parse())");