001package org.jsoup.helper; 002 003import org.jsoup.Connection; 004import org.jsoup.HttpStatusException; 005import org.jsoup.Progress; 006import org.jsoup.UnsupportedMimeTypeException; 007import org.jsoup.internal.ControllableInputStream; 008import org.jsoup.internal.StringUtil; 009import org.jsoup.nodes.Document; 010import org.jsoup.parser.Parser; 011import org.jsoup.parser.StreamParser; 012import org.jspecify.annotations.Nullable; 013 014import javax.net.ssl.SSLContext; 015import javax.net.ssl.SSLSocketFactory; 016import java.io.BufferedInputStream; 017import java.io.BufferedReader; 018import java.io.BufferedWriter; 019import java.io.ByteArrayInputStream; 020import java.io.IOException; 021import java.io.InputStream; 022import java.io.InputStreamReader; 023import java.io.OutputStream; 024import java.io.OutputStreamWriter; 025import java.io.UncheckedIOException; 026import java.net.CookieManager; 027import java.net.CookieStore; 028import java.net.InetSocketAddress; 029import java.net.MalformedURLException; 030import java.net.Proxy; 031import java.net.URL; 032import java.net.URLEncoder; 033import java.nio.Buffer; 034import java.nio.ByteBuffer; 035import java.nio.charset.Charset; 036import java.nio.charset.IllegalCharsetNameException; 037import java.nio.charset.StandardCharsets; 038import java.util.ArrayList; 039import java.util.Collection; 040import java.util.Collections; 041import java.util.LinkedHashMap; 042import java.util.List; 043import java.util.Map; 044import java.util.concurrent.locks.ReentrantLock; 045import java.util.regex.Pattern; 046import java.util.zip.GZIPInputStream; 047import java.util.zip.Inflater; 048import java.util.zip.InflaterInputStream; 049 050import static org.jsoup.Connection.Method.HEAD; 051import static org.jsoup.helper.DataUtil.UTF_8; 052import static org.jsoup.internal.Normalizer.lowerCase; 053import static org.jsoup.internal.SharedConstants.DefaultBufferSize; 054 055/** 056 * Implementation of {@link Connection}. 057 * @see org.jsoup.Jsoup#connect(String) 058 */ 059@SuppressWarnings("CharsetObjectCanBeUsed") 060public class HttpConnection implements Connection { 061 public static final String CONTENT_ENCODING = "Content-Encoding"; 062 /** 063 * Many users would get caught by not setting a user-agent and therefore getting different responses on their desktop 064 * vs in jsoup, which would otherwise default to {@code Java}. So by default, use a desktop UA. 065 */ 066 public static final String DEFAULT_UA = 067 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"; 068 private static final String USER_AGENT = "User-Agent"; 069 public static final String CONTENT_TYPE = "Content-Type"; 070 public static final String MULTIPART_FORM_DATA = "multipart/form-data"; 071 public static final String FORM_URL_ENCODED = "application/x-www-form-urlencoded"; 072 static final String DefaultUploadType = "application/octet-stream"; 073 private static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); 074 075 private HttpConnection.Request req; 076 private Connection.@Nullable Response res; 077 @Nullable Object client; // The HttpClient for this Connection, if via the HttpClientExecutor 078 @Nullable RequestAuthenticator lastAuth; // The previous Authenticator used by this Connection, if via the HttpClientExecutor 079 080 /** 081 Create a new Connection, with the request URL specified. 082 @param url the URL to fetch from 083 @return a new Connection object 084 */ 085 public static Connection connect(String url) { 086 Connection con = new HttpConnection(); 087 con.url(url); 088 return con; 089 } 090 091 /** 092 Create a new Connection, with the request URL specified. 093 @param url the URL to fetch from 094 @return a new Connection object 095 */ 096 public static Connection connect(URL url) { 097 Connection con = new HttpConnection(); 098 con.url(url); 099 return con; 100 } 101 102 /** 103 Create a new, empty HttpConnection. 104 */ 105 public HttpConnection() { 106 req = new Request(); 107 req.connection = this; 108 } 109 110 /** 111 Create a new Request by deep-copying an existing Request. Note that the data and body of the original are not 112 copied. All other settings (proxy, parser, cookies, etc) are copied. 113 @param copy the request to copy 114 */ 115 HttpConnection(Request copy) { 116 req = new Request(copy); 117 } 118 119 static String encodeMimeName(String val) { 120 return val.replace("\"", "%22"); 121 } 122 123 @Override 124 public Connection newRequest() { 125 // copy the prototype request for the different settings, cookie manager, etc 126 return new HttpConnection(req); 127 } 128 129 /** Create a new Connection that just wraps the provided Request and Response */ 130 private HttpConnection(Request req, Response res) { 131 this.req = req; 132 this.res = res; 133 } 134 135 @Override 136 public Connection url(URL url) { 137 req.url(url); 138 return this; 139 } 140 141 @Override 142 public Connection url(String url) { 143 Validate.notEmptyParam(url, "url"); 144 try { 145 req.url(new URL(url)); 146 } catch (MalformedURLException e) { 147 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); 148 } 149 return this; 150 } 151 152 @Override 153 public Connection proxy(@Nullable Proxy proxy) { 154 req.proxy(proxy); 155 return this; 156 } 157 158 @Override 159 public Connection proxy(String host, int port) { 160 req.proxy(host, port); 161 return this; 162 } 163 164 @Override 165 public Connection userAgent(String userAgent) { 166 Validate.notNullParam(userAgent, "userAgent"); 167 req.header(USER_AGENT, userAgent); 168 return this; 169 } 170 171 @Override 172 public Connection timeout(int millis) { 173 req.timeout(millis); 174 return this; 175 } 176 177 @Override 178 public Connection maxBodySize(int bytes) { 179 req.maxBodySize(bytes); 180 return this; 181 } 182 183 @Override 184 public Connection followRedirects(boolean followRedirects) { 185 req.followRedirects(followRedirects); 186 return this; 187 } 188 189 @Override 190 public Connection referrer(String referrer) { 191 Validate.notNullParam(referrer, "referrer"); 192 req.header("Referer", referrer); 193 return this; 194 } 195 196 @Override 197 public Connection method(Method method) { 198 req.method(method); 199 return this; 200 } 201 202 @Override 203 public Connection ignoreHttpErrors(boolean ignoreHttpErrors) { 204 req.ignoreHttpErrors(ignoreHttpErrors); 205 return this; 206 } 207 208 @Override 209 public Connection ignoreContentType(boolean ignoreContentType) { 210 req.ignoreContentType(ignoreContentType); 211 return this; 212 } 213 214 @Override 215 public Connection data(String key, String value) { 216 req.data(KeyVal.create(key, value)); 217 return this; 218 } 219 220 @Override 221 @Deprecated 222 public Connection sslSocketFactory(SSLSocketFactory sslSocketFactory) { 223 req.sslSocketFactory(sslSocketFactory); 224 return this; 225 } 226 227 @Override 228 public Connection sslContext(SSLContext sslContext) { 229 req.sslContext(sslContext); 230 return this; 231 } 232 233 @Override 234 public Connection data(String key, String filename, InputStream inputStream) { 235 req.data(KeyVal.create(key, filename, inputStream)); 236 return this; 237 } 238 239 @Override 240 public Connection data(String key, String filename, InputStream inputStream, String contentType) { 241 req.data(KeyVal.create(key, filename, inputStream).contentType(contentType)); 242 return this; 243 } 244 245 @Override 246 public Connection data(Map<String, String> data) { 247 Validate.notNullParam(data, "data"); 248 for (Map.Entry<String, String> entry : data.entrySet()) { 249 req.data(KeyVal.create(entry.getKey(), entry.getValue())); 250 } 251 return this; 252 } 253 254 @Override 255 public Connection data(String... keyvals) { 256 Validate.notNullParam(keyvals, "keyvals"); 257 Validate.isTrue(keyvals.length %2 == 0, "Must supply an even number of key value pairs"); 258 for (int i = 0; i < keyvals.length; i += 2) { 259 String key = keyvals[i]; 260 String value = keyvals[i+1]; 261 Validate.notEmpty(key, "Data key must not be empty"); 262 Validate.notNull(value, "Data value must not be null"); 263 req.data(KeyVal.create(key, value)); 264 } 265 return this; 266 } 267 268 @Override 269 public Connection data(Collection<Connection.KeyVal> data) { 270 Validate.notNullParam(data, "data"); 271 for (Connection.KeyVal entry: data) { 272 req.data(entry); 273 } 274 return this; 275 } 276 277 @Override 278 public Connection.@Nullable KeyVal data(String key) { 279 Validate.notEmptyParam(key, "key"); 280 for (Connection.KeyVal keyVal : request().data()) { 281 if (keyVal.key().equals(key)) 282 return keyVal; 283 } 284 return null; 285 } 286 287 @Override 288 public Connection requestBody(String body) { 289 req.requestBody(body); 290 return this; 291 } 292 293 @Override 294 public Connection requestBodyStream(InputStream stream) { 295 req.requestBodyStream(stream); 296 return this; 297 } 298 299 @Override 300 public Connection header(String name, String value) { 301 req.header(name, value); 302 return this; 303 } 304 305 @Override 306 public Connection headers(Map<String,String> headers) { 307 Validate.notNullParam(headers, "headers"); 308 for (Map.Entry<String,String> entry : headers.entrySet()) { 309 req.header(entry.getKey(),entry.getValue()); 310 } 311 return this; 312 } 313 314 @Override 315 public Connection cookie(String name, String value) { 316 req.cookie(name, value); 317 return this; 318 } 319 320 @Override 321 public Connection cookies(Map<String, String> cookies) { 322 Validate.notNullParam(cookies, "cookies"); 323 for (Map.Entry<String, String> entry : cookies.entrySet()) { 324 req.cookie(entry.getKey(), entry.getValue()); 325 } 326 return this; 327 } 328 329 @Override 330 public Connection cookieStore(CookieStore cookieStore) { 331 // create a new cookie manager using the new store 332 req.cookieManager = new CookieManager(cookieStore, null); 333 return this; 334 } 335 336 @Override 337 public CookieStore cookieStore() { 338 return req.cookieManager.getCookieStore(); 339 } 340 341 @Override 342 public Connection parser(Parser parser) { 343 req.parser(parser); 344 return this; 345 } 346 347 @Override 348 public Document get() throws IOException { 349 req.method(Method.GET); 350 execute(); 351 Validate.notNull(res); 352 return res.parse(); 353 } 354 355 @Override 356 public Document post() throws IOException { 357 req.method(Method.POST); 358 execute(); 359 Validate.notNull(res); 360 return res.parse(); 361 } 362 363 @Override 364 public Connection.Response execute() throws IOException { 365 res = Response.execute(req); 366 return res; 367 } 368 369 @Override 370 public Connection.Request request() { 371 return req; 372 } 373 374 @Override 375 public Connection request(Connection.Request request) { 376 req = (HttpConnection.Request) request; // will throw a class-cast exception if the user has extended some but not all of Connection; that's desired 377 return this; 378 } 379 380 @Override 381 public Connection.Response response() { 382 if (res == null) { 383 throw new IllegalArgumentException("You must execute the request before getting a response."); 384 } 385 return res; 386 } 387 388 @Override 389 public Connection response(Connection.Response response) { 390 res = response; 391 return this; 392 } 393 394 @Override 395 public Connection postDataCharset(String charset) { 396 req.postDataCharset(charset); 397 return this; 398 } 399 400 @Override public Connection auth(@Nullable RequestAuthenticator authenticator) { 401 req.auth(authenticator); 402 return this; 403 } 404 405 @Override public Connection onResponseProgress(Progress<Connection.Response> handler) { 406 req.responseProgress = handler; 407 return this; 408 } 409 410 @SuppressWarnings("unchecked") 411 private static abstract class Base<T extends Connection.Base<T>> implements Connection.Base<T> { 412 private static final URL UnsetUrl; // only used if you created a new Request() 413 static { 414 try { 415 UnsetUrl = new URL("http://undefined/"); 416 } catch (MalformedURLException e) { 417 throw new IllegalStateException(e); 418 } 419 } 420 421 URL url = UnsetUrl; 422 Method method = Method.GET; 423 Map<String, List<String>> headers; 424 Map<String, String> cookies; 425 426 private Base() { 427 headers = new LinkedHashMap<>(); 428 cookies = new LinkedHashMap<>(); 429 } 430 431 private Base(Base<T> copy) { 432 url = copy.url; // unmodifiable object 433 method = copy.method; 434 headers = new LinkedHashMap<>(); 435 for (Map.Entry<String, List<String>> entry : copy.headers.entrySet()) { 436 headers.put(entry.getKey(), new ArrayList<>(entry.getValue())); 437 } 438 cookies = new LinkedHashMap<>(); cookies.putAll(copy.cookies); // just holds strings 439 } 440 441 @Override 442 public URL url() { 443 if (url == UnsetUrl) 444 throw new IllegalArgumentException("URL not set. Make sure to call #url(...) before executing the request."); 445 return url; 446 } 447 448 @Override 449 public T url(URL url) { 450 Validate.notNullParam(url, "url"); 451 this.url = new UrlBuilder(url).build(); 452 return (T) this; 453 } 454 455 @Override 456 public Method method() { 457 return method; 458 } 459 460 @Override 461 public T method(Method method) { 462 Validate.notNullParam(method, "method"); 463 this.method = method; 464 return (T) this; 465 } 466 467 @Override @Nullable 468 public String header(String name) { 469 Validate.notNullParam(name, "name"); 470 List<String> vals = getHeadersCaseInsensitive(name); 471 if (!vals.isEmpty()) { 472 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 473 return StringUtil.join(vals, ", "); 474 } 475 476 return null; 477 } 478 479 @Override 480 public T addHeader(String name, @Nullable String value) { 481 Validate.notEmptyParam(name, "name"); 482 value = value == null ? "" : value; 483 484 List<String> values = headers(name); 485 if (values.isEmpty()) { 486 values = new ArrayList<>(); 487 headers.put(name, values); 488 } 489 values.add(value); 490 491 return (T) this; 492 } 493 494 @Override 495 public List<String> headers(String name) { 496 Validate.notEmptyParam(name, "name"); 497 return getHeadersCaseInsensitive(name); 498 } 499 500 @Override 501 public T header(String name, String value) { 502 Validate.notEmptyParam(name, "name"); 503 removeHeader(name); // ensures we don't get an "accept-encoding" and an "Accept-Encoding" 504 addHeader(name, value); 505 return (T) this; 506 } 507 508 @Override 509 public boolean hasHeader(String name) { 510 Validate.notEmptyParam(name, "name"); 511 return !getHeadersCaseInsensitive(name).isEmpty(); 512 } 513 514 /** 515 * Test if the request has a header with this value (case-insensitive). 516 */ 517 @Override 518 public boolean hasHeaderWithValue(String name, String value) { 519 Validate.notEmpty(name); 520 Validate.notEmpty(value); 521 List<String> values = headers(name); 522 for (String candidate : values) { 523 if (value.equalsIgnoreCase(candidate)) 524 return true; 525 } 526 return false; 527 } 528 529 @Override 530 public T removeHeader(String name) { 531 Validate.notEmptyParam(name, "name"); 532 Map.Entry<String, List<String>> entry = scanHeaders(name); // remove is case-insensitive too 533 if (entry != null) 534 headers.remove(entry.getKey()); // ensures correct case 535 return (T) this; 536 } 537 538 @Override 539 public Map<String, String> headers() { 540 LinkedHashMap<String, String> map = new LinkedHashMap<>(headers.size()); 541 for (Map.Entry<String, List<String>> entry : headers.entrySet()) { 542 String header = entry.getKey(); 543 List<String> values = entry.getValue(); 544 if (!values.isEmpty()) 545 map.put(header, values.get(0)); 546 } 547 return map; 548 } 549 550 @Override 551 public Map<String, List<String>> multiHeaders() { 552 return headers; 553 } 554 555 private List<String> getHeadersCaseInsensitive(String name) { 556 Validate.notNull(name); 557 558 for (Map.Entry<String, List<String>> entry : headers.entrySet()) { 559 if (name.equalsIgnoreCase(entry.getKey())) 560 return entry.getValue(); 561 } 562 563 return Collections.emptyList(); 564 } 565 566 private Map.@Nullable Entry<String, List<String>> scanHeaders(String name) { 567 String lc = lowerCase(name); 568 for (Map.Entry<String, List<String>> entry : headers.entrySet()) { 569 if (lowerCase(entry.getKey()).equals(lc)) 570 return entry; 571 } 572 return null; 573 } 574 575 @Override 576 public String cookie(String name) { 577 Validate.notEmptyParam(name, "name"); 578 return cookies.get(name); 579 } 580 581 @Override 582 public T cookie(String name, String value) { 583 Validate.notEmptyParam(name, "name"); 584 Validate.notNullParam(value, "value"); 585 cookies.put(name, value); 586 return (T) this; 587 } 588 589 @Override 590 public boolean hasCookie(String name) { 591 Validate.notEmptyParam(name, "name"); 592 return cookies.containsKey(name); 593 } 594 595 @Override 596 public T removeCookie(String name) { 597 Validate.notEmptyParam(name, "name"); 598 cookies.remove(name); 599 return (T) this; 600 } 601 602 @Override 603 public Map<String, String> cookies() { 604 return cookies; 605 } 606 } 607 608 public static class Request extends HttpConnection.Base<Connection.Request> implements Connection.Request { 609 static { 610 System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); 611 // make sure that we can send Sec-Fetch-Site headers etc. 612 } 613 614 HttpConnection connection; 615 private @Nullable Proxy proxy; 616 private int timeoutMilliseconds; 617 private int maxBodySizeBytes; 618 private boolean followRedirects; 619 private final Collection<Connection.KeyVal> data; 620 private @Nullable Object body = null; // String or InputStream 621 @Nullable String mimeBoundary; 622 private boolean ignoreHttpErrors = false; 623 private boolean ignoreContentType = false; 624 private Parser parser; 625 private boolean parserDefined = false; // called parser(...) vs initialized in ctor 626 private String postDataCharset = DataUtil.defaultCharsetName; 627 private @Nullable SSLSocketFactory sslSocketFactory; 628 @Nullable SSLContext sslContext; 629 private CookieManager cookieManager; 630 @Nullable RequestAuthenticator authenticator; 631 private @Nullable Progress<Connection.Response> responseProgress; 632 633 private final ReentrantLock executing = new ReentrantLock(); // detects and warns if same request used concurrently 634 635 Request() { 636 super(); 637 timeoutMilliseconds = 30000; // 30 seconds 638 maxBodySizeBytes = 1024 * 1024 * 2; // 2MB 639 followRedirects = true; 640 data = new ArrayList<>(); 641 method = Method.GET; 642 addHeader("Accept-Encoding", "gzip"); 643 addHeader(USER_AGENT, DEFAULT_UA); 644 parser = Parser.htmlParser(); 645 cookieManager = new CookieManager(); // creates a default InMemoryCookieStore 646 } 647 648 Request(Request copy) { 649 super(copy); 650 connection = copy.connection; 651 proxy = copy.proxy; 652 postDataCharset = copy.postDataCharset; 653 timeoutMilliseconds = copy.timeoutMilliseconds; 654 maxBodySizeBytes = copy.maxBodySizeBytes; 655 followRedirects = copy.followRedirects; 656 data = new ArrayList<>(); // data not copied 657 //body not copied 658 ignoreHttpErrors = copy.ignoreHttpErrors; 659 ignoreContentType = copy.ignoreContentType; 660 parser = copy.parser.newInstance(); // parsers and their tree-builders maintain state, so need a fresh copy 661 parserDefined = copy.parserDefined; 662 sslSocketFactory = copy.sslSocketFactory; // these are all synchronized so safe to share 663 sslContext = copy.sslContext; 664 cookieManager = copy.cookieManager; 665 authenticator = copy.authenticator; 666 responseProgress = copy.responseProgress; 667 } 668 669 @Override @Nullable 670 public Proxy proxy() { 671 return proxy; 672 } 673 674 @Override 675 public Request proxy(@Nullable Proxy proxy) { 676 this.proxy = proxy; 677 return this; 678 } 679 680 @Override 681 public Request proxy(String host, int port) { 682 this.proxy = new Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(host, port)); 683 return this; 684 } 685 686 @Override 687 public int timeout() { 688 return timeoutMilliseconds; 689 } 690 691 @Override 692 public Request timeout(int millis) { 693 Validate.isTrue(millis >= 0, "Timeout milliseconds must be 0 (infinite) or greater"); 694 timeoutMilliseconds = millis; 695 return this; 696 } 697 698 @Override 699 public int maxBodySize() { 700 return maxBodySizeBytes; 701 } 702 703 @Override 704 public Connection.Request maxBodySize(int bytes) { 705 Validate.isTrue(bytes >= 0, "maxSize must be 0 (unlimited) or larger"); 706 maxBodySizeBytes = bytes; 707 return this; 708 } 709 710 @Override 711 public boolean followRedirects() { 712 return followRedirects; 713 } 714 715 @Override 716 public Connection.Request followRedirects(boolean followRedirects) { 717 this.followRedirects = followRedirects; 718 return this; 719 } 720 721 @Override 722 public boolean ignoreHttpErrors() { 723 return ignoreHttpErrors; 724 } 725 726 @Override @Nullable 727 public SSLSocketFactory sslSocketFactory() { 728 return sslSocketFactory; 729 } 730 731 @Override 732 @Deprecated 733 public void sslSocketFactory(SSLSocketFactory sslSocketFactory) { 734 this.sslSocketFactory = sslSocketFactory; 735 } 736 737 @Override @Nullable 738 public SSLContext sslContext() { 739 return sslContext; 740 } 741 742 @Override 743 public Connection.Request sslContext(SSLContext sslContext) { 744 this.sslContext = sslContext; 745 return this; 746 } 747 748 @Override 749 public Connection.Request ignoreHttpErrors(boolean ignoreHttpErrors) { 750 this.ignoreHttpErrors = ignoreHttpErrors; 751 return this; 752 } 753 754 @Override 755 public boolean ignoreContentType() { 756 return ignoreContentType; 757 } 758 759 @Override 760 public Connection.Request ignoreContentType(boolean ignoreContentType) { 761 this.ignoreContentType = ignoreContentType; 762 return this; 763 } 764 765 @Override 766 public Request data(Connection.KeyVal keyval) { 767 Validate.notNullParam(keyval, "keyval"); 768 data.add(keyval); 769 return this; 770 } 771 772 @Override 773 public Collection<Connection.KeyVal> data() { 774 return data; 775 } 776 777 @Override 778 public Connection.Request requestBody(@Nullable String body) { 779 this.body = body; 780 return this; 781 } 782 783 @Override @Nullable 784 public String requestBody() { 785 return body instanceof String ? (String) body : null; 786 } 787 788 @Override 789 public Connection.Request requestBodyStream(InputStream stream) { 790 body = stream; 791 return this; 792 } 793 794 @Override 795 public Request parser(Parser parser) { 796 this.parser = parser; 797 parserDefined = true; 798 return this; 799 } 800 801 @Override 802 public Parser parser() { 803 return parser; 804 } 805 806 @Override 807 public Connection.Request postDataCharset(String charset) { 808 Validate.notNullParam(charset, "charset"); 809 if (!Charset.isSupported(charset)) throw new IllegalCharsetNameException(charset); 810 this.postDataCharset = charset; 811 return this; 812 } 813 814 @Override 815 public String postDataCharset() { 816 return postDataCharset; 817 } 818 819 CookieManager cookieManager() { 820 return cookieManager; 821 } 822 823 @Override public Connection.Request auth(@Nullable RequestAuthenticator authenticator) { 824 this.authenticator = authenticator; 825 return this; 826 } 827 828 @Override @Nullable public RequestAuthenticator auth() { 829 return authenticator; 830 } 831 } 832 833 public static class Response extends HttpConnection.Base<Connection.Response> implements Connection.Response { 834 private static final int MAX_REDIRECTS = 20; 835 private static final String LOCATION = "Location"; 836 private static final String[] REDIRECT_CONTENT_HEADERS = { 837 CONTENT_ENCODING, "Content-Language", "Content-Location", CONTENT_TYPE, "Content-Length", "Digest", "Last-Modified" 838 }; 839 int statusCode; 840 String statusMessage = ""; 841 private @Nullable ByteBuffer byteData; 842 private @Nullable ControllableInputStream bodyStream; 843 @Nullable RequestExecutor executor; 844 private @Nullable String charset; 845 @Nullable String contentType; 846 int contentLength; 847 private boolean executed = false; 848 private boolean inputStreamRead = false; 849 private int numRedirects = 0; 850 private final HttpConnection.Request req; 851 852 /* 853 * Matches XML content types (like text/xml, image/svg+xml, application/xhtml+xml;charset=UTF8, etc) 854 */ 855 private static final Pattern xmlContentTypeRxp = Pattern.compile("(\\w+)/\\w*\\+?xml.*"); 856 857 /** 858 <b>Internal only! </b>Creates a dummy HttpConnection.Response, useful for testing. All actual responses 859 are created from the HttpURLConnection and fields defined. 860 */ 861 Response() { 862 super(); 863 statusCode = 400; 864 statusMessage = "Request not made"; 865 req = new Request(); 866 contentType = null; 867 } 868 869 static Response execute(HttpConnection.Request req) throws IOException { 870 return execute(req, null); 871 } 872 873 /** 874 Determines the request method for an automatic redirect, or null if the status is not automatically redirected. 875 See <a href="https://www.rfc-editor.org/rfc/rfc9110.html#section-15.4">RFC 9110, Section 15.4</a>. 876 */ 877 static @Nullable Method redirectMethod(int statusCode, Method method) { 878 switch (statusCode) { 879 case 301: // Moved Permanently 880 case 302: // Found 881 return method == Method.POST ? Method.GET : method; 882 case 303: // See Other 883 return method == Method.HEAD ? Method.HEAD : Method.GET; 884 case 307: // Temporary Redirect 885 case 308: // Permanent Redirect 886 return method; 887 default: 888 return null; 889 } 890 } 891 892 /** 893 Tests if two URLs share an HTTP origin, as defined by scheme, host, and effective port. 894 See <a href="https://www.rfc-editor.org/rfc/rfc9110.html#section-4.3.1">RFC 9110, Section 4.3.1</a>. 895 */ 896 static boolean sameOrigin(URL first, URL second) { 897 int firstPort = first.getPort() != -1 ? first.getPort() : first.getDefaultPort(); 898 int secondPort = second.getPort() != -1 ? second.getPort() : second.getDefaultPort(); 899 return first.getProtocol().equalsIgnoreCase(second.getProtocol()) 900 && first.getHost().equalsIgnoreCase(second.getHost()) 901 && firstPort == secondPort; 902 } 903 904 static Response execute(HttpConnection.Request req, @Nullable Response prevRes) throws IOException { 905 Validate.isTrue(req.executing.tryLock(), "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."); 906 Validate.notNullParam(req, "req"); 907 URL url = req.url(); 908 Validate.notNull(url, "URL must be specified to connect"); 909 String protocol = url.getProtocol(); 910 if (!protocol.equals("http") && !protocol.equals("https")) 911 throw new MalformedURLException("Only http & https protocols supported"); 912 final boolean supportsBody = req.method().hasBody(); 913 final boolean hasBody = req.body != null; 914 if (!supportsBody) 915 Validate.isFalse(hasBody, "Cannot set a request body for HTTP method " + req.method()); 916 917 // set up the request for execution 918 if (!req.data().isEmpty() && (!supportsBody || hasBody)) 919 serialiseRequestUrl(req); 920 else if (supportsBody) 921 setOutputContentType(req); 922 923 long startTime = System.nanoTime(); 924 RequestExecutor executor = RequestDispatch.get(req, prevRes); 925 Response res = null; 926 try { 927 res = executor.execute(); 928 929 Method nextMethod = redirectMethod(res.statusCode, req.method()); 930 if (nextMethod != null && res.hasHeader(LOCATION) && req.followRedirects()) { 931 if (nextMethod == req.method() && (req.body instanceof InputStream || needsMultipart(req))) 932 throw new IOException("Cannot follow redirect with a streamed request body; disable followRedirects and resend with a fresh stream"); 933 934 if (nextMethod != req.method()) { 935 req.method(nextMethod); 936 req.data().clear(); 937 req.requestBody(null); 938 for (String header : REDIRECT_CONTENT_HEADERS) 939 req.removeHeader(header); 940 } 941 942 String location = res.header(LOCATION); 943 Validate.notNull(location); 944 if (location.startsWith("http:/") && location.charAt(6) != '/') // fix broken Location: http:/temp/AAG_New/en/index.php 945 location = location.substring(6); 946 URL redir = StringUtil.resolve(req.url(), location); 947 if (!sameOrigin(req.url(), redir)) { 948 // remove sensitive headers; defense-in-depth against open redirects 949 req.removeHeader("Authorization"); 950 req.removeHeader("Cookie"); 951 req.removeHeader("Cookie2"); 952 req.cookies().clear(); 953 } 954 req.url(redir); 955 956 return execute(req, res); 957 } 958 if ((res.statusCode < 200 || res.statusCode >= 400) && !req.ignoreHttpErrors()) 959 throw new HttpStatusException("HTTP error fetching URL", res.statusCode, req.url().toString()); 960 961 // check that we can handle the returned content type; if not, abort before fetching it 962 String contentType = res.contentType(); 963 if (contentType != null 964 && !req.ignoreContentType() 965 && !contentType.startsWith("text/") 966 && !xmlContentTypeRxp.matcher(contentType).matches() 967 ) 968 throw new UnsupportedMimeTypeException("Unhandled content type. Must be text/*, */xml, or */*+xml", 969 contentType, req.url().toString()); 970 971 // switch to the XML parser if content type is xml and not parser not explicitly set 972 if (contentType != null && xmlContentTypeRxp.matcher(contentType).matches()) { 973 if (!req.parserDefined) req.parser(Parser.xmlParser()); 974 } 975 976 res.charset = DataUtil.getCharsetFromContentType(res.contentType); // may be null, readInputStream deals with it 977 if (res.contentLength != 0 && req.method() != HEAD) { // -1 means unknown, chunked. sun throws an IO exception on 500 response with no content when trying to read body 978 InputStream stream = executor.responseBody(); 979 if (res.hasHeaderWithValue(CONTENT_ENCODING, "gzip")) 980 stream = new GZIPInputStream(stream); 981 else if (res.hasHeaderWithValue(CONTENT_ENCODING, "deflate")) 982 stream = new InflaterInputStream(stream, new Inflater(true)); 983 984 res.bodyStream = ControllableInputStream.wrap( 985 stream, DefaultBufferSize, req.maxBodySize()) 986 .timeout(startTime, req.timeout()); 987 988 if (req.responseProgress != null) // set response progress listener 989 res.bodyStream.onProgress(res.contentLength, req.responseProgress, res); 990 } else { 991 res.byteData = DataUtil.emptyByteBuffer(); 992 } 993 } catch (IOException e) { 994 if (res != null) res.safeClose(); // will be non-null if got to conn 995 throw e; 996 } finally { 997 req.executing.unlock(); 998 999 // detach any thread local auth delegate 1000 if (req.authenticator != null) 1001 AuthenticationHandler.handler.remove(); 1002 } 1003 1004 res.executed = true; 1005 return res; 1006 } 1007 1008 @Override 1009 public int statusCode() { 1010 return statusCode; 1011 } 1012 1013 @Override 1014 public String statusMessage() { 1015 return statusMessage; 1016 } 1017 1018 @Override @Nullable 1019 public String charset() { 1020 return charset; 1021 } 1022 1023 @Override 1024 public Response charset(String charset) { 1025 this.charset = charset; 1026 return this; 1027 } 1028 1029 @Override @Nullable 1030 public String contentType() { 1031 return contentType; 1032 } 1033 1034 /** Called from parse() or streamParser(), validates and prepares the input stream, and aligns common settings. */ 1035 private ControllableInputStream prepareParse() { 1036 Validate.isTrue(executed, "Request must be executed (with .execute(), .get(), or .post() before parsing response"); 1037 ControllableInputStream stream = bodyStream; 1038 if (byteData != null) { // bytes have been read in to the buffer, parse that 1039 ByteArrayInputStream bytes = new ByteArrayInputStream(byteData.array(), 0, byteData.limit()); 1040 stream = ControllableInputStream.wrap(bytes, 0); // no max 1041 inputStreamRead = false; // ok to reparse if in bytes 1042 } 1043 Validate.isFalse(inputStreamRead, "Input stream already read and parsed, cannot re-read."); 1044 Validate.notNull(stream); 1045 inputStreamRead = true; 1046 return stream; 1047 } 1048 1049 @Override public Document parse() throws IOException { 1050 ControllableInputStream stream = prepareParse(); 1051 Document doc = DataUtil.parseInputStream(stream, charset, url.toExternalForm(), req.parser()); 1052 doc.connection(new HttpConnection(req, this)); // because we're static, don't have the connection obj. // todo - maybe hold in the req? 1053 charset = doc.outputSettings().charset().name(); // update charset from meta-equiv, possibly 1054 safeClose(); 1055 return doc; 1056 } 1057 1058 @Override public StreamParser streamParser() throws IOException { 1059 ControllableInputStream stream = prepareParse(); 1060 String baseUri = url.toExternalForm(); 1061 DataUtil.CharsetDoc charsetDoc = DataUtil.detectCharsetForStreamParser(stream, charset, baseUri, req.parser()); 1062 1063 // set up the stream parser and rig this connection up to the parsed doc: 1064 StreamParser streamer = new StreamParser(req.parser()); 1065 BufferedReader reader = new BufferedReader(new InputStreamReader(charsetDoc.input, charsetDoc.charset)); 1066 streamer.parse(reader, baseUri); // initializes the parse and the document, but does not step() it 1067 streamer.document().connection(new HttpConnection(req, this)); 1068 charset = charsetDoc.charset.name(); 1069 1070 // we don't safeClose() as in parse(); caller must close streamParser to close InputStream stream 1071 return streamer; 1072 } 1073 1074 /** 1075 Reads the bodyStream into byteData. A no-op if already executed. 1076 */ 1077 @Override 1078 public Connection.Response readFully() throws IOException { 1079 Validate.isTrue(executed, "Request must be executed (with .execute(), .get(), or .post() before getting response body"); 1080 if (bodyStream != null && byteData == null) { 1081 Validate.isFalse(inputStreamRead, "Request has already been read (with .parse())"); 1082 try { 1083 byteData = DataUtil.readToByteBuffer(bodyStream, req.maxBodySize()); 1084 } finally { 1085 inputStreamRead = true; 1086 safeClose(); 1087 } 1088 } 1089 return this; 1090 } 1091 1092 /** 1093 Reads the body, but throws an UncheckedIOException if an IOException occurs. 1094 @throws UncheckedIOException if an IOException occurs 1095 */ 1096 private void readByteDataUnchecked() { 1097 try { 1098 readFully(); 1099 } catch (IOException e) { 1100 throw new UncheckedIOException(e); 1101 } 1102 } 1103 1104 @Override 1105 public String readBody() throws IOException { 1106 readFully(); 1107 return body(); 1108 } 1109 1110 @Override 1111 public String body() { 1112 readByteDataUnchecked(); 1113 Validate.notNull(byteData); 1114 // charset gets set from header on execute, and from meta-equiv on parse. parse may not have happened yet 1115 String body = (charset == null ? UTF_8 : Charset.forName(charset)) 1116 .decode(byteData).toString(); 1117 ((Buffer)byteData).rewind(); // cast to avoid covariant return type change in jdk9 1118 return body; 1119 } 1120 1121 @Override 1122 public byte[] bodyAsBytes() { 1123 readByteDataUnchecked(); 1124 Validate.notNull(byteData); 1125 Validate.isTrue(byteData.hasArray()); // we made it, so it should 1126 1127 byte[] array = byteData.array(); 1128 int offset = byteData.arrayOffset(); 1129 int length = byteData.limit(); 1130 1131 if (offset == 0 && length == array.length) { // exact, just return it 1132 return array; 1133 } else { // trim to size 1134 byte[] exactArray = new byte[length]; 1135 System.arraycopy(array, offset, exactArray, 0, length); 1136 return exactArray; 1137 } 1138 } 1139 1140 @Override 1141 @Deprecated 1142 public Connection.Response bufferUp() { 1143 readByteDataUnchecked(); 1144 return this; 1145 } 1146 1147 @Override 1148 public BufferedInputStream bodyStream() { 1149 Validate.isTrue(executed, "Request must be executed (with .execute(), .get(), or .post() before getting response body"); 1150 1151 // if we have read to bytes (via readFully), return those as a stream. 1152 if (byteData != null) { 1153 return new BufferedInputStream( 1154 new ByteArrayInputStream(byteData.array(), 0, byteData.limit()), 1155 DefaultBufferSize); 1156 } 1157 1158 Validate.isFalse(inputStreamRead, "Request has already been read"); 1159 Validate.notNull(bodyStream); 1160 inputStreamRead = true; 1161 return bodyStream.inputStream(); 1162 } 1163 1164 /** 1165 * Call on completion of stream read, to close the body (or error) stream. The connection.disconnect allows 1166 * keep-alives to work (as the underlying connection is actually held open, despite the name). 1167 */ 1168 private void safeClose() { 1169 if (bodyStream != null) { 1170 try { 1171 bodyStream.close(); 1172 } catch (IOException e) { 1173 // no-op 1174 } finally { 1175 bodyStream = null; 1176 } 1177 } 1178 1179 if (executor != null) executor.safeClose(); // disconnect 1180 } 1181 1182 Response(HttpConnection.Request request) { 1183 this.req = request; 1184 } 1185 1186 // set up url, method, header, cookies 1187 void prepareResponse(Map<String, List<String>> resHeaders, HttpConnection.@Nullable Response previousResponse) throws IOException { 1188 processResponseHeaders(resHeaders); // includes cookie key/val read during header scan 1189 CookieUtil.storeCookies(req, this, url, resHeaders); // add set cookies to cookie store 1190 1191 if (previousResponse != null) { // was redirected 1192 // map previous response cookies into this response cookies() object 1193 for (Map.Entry<String, String> prevCookie : previousResponse.cookies().entrySet()) { 1194 if (!hasCookie(prevCookie.getKey())) 1195 cookie(prevCookie.getKey(), prevCookie.getValue()); 1196 } 1197 previousResponse.safeClose(); 1198 1199 // enforce too many redirects: 1200 numRedirects = previousResponse.numRedirects + 1; 1201 if (numRedirects >= MAX_REDIRECTS) 1202 throw new IOException(String.format("Too many redirects occurred trying to load URL %s", previousResponse.url())); 1203 } 1204 } 1205 1206 void processResponseHeaders(Map<String, List<String>> resHeaders) { 1207 for (Map.Entry<String, List<String>> entry : resHeaders.entrySet()) { 1208 String name = entry.getKey(); 1209 if (name == null) 1210 continue; // http/1.1 line 1211 1212 List<String> values = entry.getValue(); 1213 for (String value : values) { 1214 addHeader(name, fixHeaderEncoding(value)); 1215 } 1216 } 1217 } 1218 1219 /** 1220 Servers may encode response headers in UTF-8 instead of RFC defined 8859. The JVM decodes the headers (before we see them) as 8859, which can lead to mojibake data. 1221 <p>This method attempts to detect that and re-decode the string as UTF-8.</p> 1222 <p>However on Android, the headers will be decoded as UTF8, so we can detect and pass those directly.</p> 1223 * @param val a header value string that may have been incorrectly decoded as 8859. 1224 * @return a potentially re-decoded string. 1225 */ 1226 @Nullable 1227 static String fixHeaderEncoding(@Nullable String val) { 1228 if (val == null) return val; 1229 // If we can't encode the string as 8859, then it couldn't have been decoded as 8859 1230 if (!StandardCharsets.ISO_8859_1.newEncoder().canEncode(val)) 1231 return val; 1232 byte[] bytes = val.getBytes(ISO_8859_1); 1233 if (looksLikeUtf8(bytes)) 1234 return new String(bytes, UTF_8); 1235 else 1236 return val; 1237 } 1238 1239 private static boolean looksLikeUtf8(byte[] input) { 1240 int i = 0; 1241 // BOM: 1242 if (input.length >= 3 1243 && (input[0] & 0xFF) == 0xEF 1244 && (input[1] & 0xFF) == 0xBB 1245 && (input[2] & 0xFF) == 0xBF) { 1246 i = 3; 1247 } 1248 1249 int end; 1250 boolean foundNonAscii = false; 1251 for (int j = input.length; i < j; ++i) { 1252 int o = input[i]; 1253 if ((o & 0x80) == 0) { 1254 continue; // ASCII 1255 } 1256 foundNonAscii = true; 1257 1258 // UTF-8 leading: 1259 if ((o & 0xE0) == 0xC0) { 1260 end = i + 1; 1261 } else if ((o & 0xF0) == 0xE0) { 1262 end = i + 2; 1263 } else if ((o & 0xF8) == 0xF0) { 1264 end = i + 3; 1265 } else { 1266 return false; 1267 } 1268 1269 if (end >= input.length) 1270 return false; 1271 1272 while (i < end) { 1273 i++; 1274 o = input[i]; 1275 if ((o & 0xC0) != 0x80) { 1276 return false; 1277 } 1278 } 1279 } 1280 return foundNonAscii; 1281 } 1282 1283 private static void setOutputContentType(final HttpConnection.Request req) { 1284 final String contentType = req.header(CONTENT_TYPE); 1285 String bound = contentType != null && contentType.contains(MULTIPART_FORM_DATA) ? req.mimeBoundary : null; 1286 if (contentType != null) { 1287 // no-op; don't add content type as already set (e.g. for requestBody()) 1288 // todo - if content type already set, we could add charset 1289 1290 // if user has set content type to multipart/form-data, auto add boundary. 1291 if(contentType.contains(MULTIPART_FORM_DATA) && !contentType.contains("boundary")) { 1292 bound = DataUtil.mimeBoundary(); 1293 req.header(CONTENT_TYPE, MULTIPART_FORM_DATA + "; boundary=" + bound); 1294 } 1295 1296 } 1297 else if (needsMultipart(req)) { 1298 bound = DataUtil.mimeBoundary(); 1299 req.header(CONTENT_TYPE, MULTIPART_FORM_DATA + "; boundary=" + bound); 1300 } else { 1301 req.header(CONTENT_TYPE, FORM_URL_ENCODED + "; charset=" + req.postDataCharset()); 1302 } 1303 req.mimeBoundary = bound; 1304 } 1305 1306 static void writePost(final HttpConnection.Request req, final OutputStream outputStream) throws IOException { 1307 try (OutputStreamWriter osw = new OutputStreamWriter(outputStream, req.postDataCharset()); 1308 BufferedWriter w = new BufferedWriter(osw)) { 1309 implWritePost(req, w, outputStream); 1310 } 1311 } 1312 1313 private static void implWritePost(final HttpConnection.Request req, final BufferedWriter w, final OutputStream outputStream) throws IOException { 1314 final Collection<Connection.KeyVal> data = req.data(); 1315 final String boundary = req.mimeBoundary; 1316 1317 if (boundary != null) { // a multipart post 1318 for (Connection.KeyVal keyVal : data) { 1319 w.write("--"); 1320 w.write(boundary); 1321 w.write("\r\n"); 1322 w.write("Content-Disposition: form-data; name=\""); 1323 w.write(encodeMimeName(keyVal.key())); // encodes " to %22 1324 w.write("\""); 1325 final InputStream input = keyVal.inputStream(); 1326 if (input != null) { 1327 w.write("; filename=\""); 1328 w.write(encodeMimeName(keyVal.value())); 1329 w.write("\"\r\nContent-Type: "); 1330 String contentType = keyVal.contentType(); 1331 w.write(contentType != null ? contentType : DefaultUploadType); 1332 w.write("\r\n\r\n"); 1333 w.flush(); 1334 DataUtil.crossStreams(input, outputStream); 1335 outputStream.flush(); 1336 } else { 1337 w.write("\r\n\r\n"); 1338 w.write(keyVal.value()); 1339 } 1340 w.write("\r\n"); 1341 } 1342 w.write("--"); 1343 w.write(boundary); 1344 w.write("--"); 1345 } else if (req.body != null) { // a single body (bytes or plain text); data will be in query string 1346 if (req.body instanceof String) { 1347 w.write((String) req.body); 1348 } else if (req.body instanceof InputStream) { 1349 DataUtil.crossStreams((InputStream) req.body, outputStream); 1350 outputStream.flush(); 1351 } else { 1352 throw new IllegalStateException(); 1353 } 1354 } else { // regular form data (application/x-www-form-urlencoded) 1355 boolean first = true; 1356 for (Connection.KeyVal keyVal : data) { 1357 if (!first) w.append('&'); 1358 else first = false; 1359 1360 w.write(URLEncoder.encode(keyVal.key(), req.postDataCharset())); 1361 w.write('='); 1362 w.write(URLEncoder.encode(keyVal.value(), req.postDataCharset())); 1363 } 1364 } 1365 } 1366 1367 // for get url reqs, serialise the data map into the url 1368 private static void serialiseRequestUrl(Connection.Request req) throws IOException { 1369 UrlBuilder in = new UrlBuilder(req.url()); 1370 1371 for (Connection.KeyVal keyVal : req.data()) { 1372 Validate.isFalse(keyVal.hasInputStream(), "InputStream data not supported in URL query string."); 1373 in.appendKeyVal(keyVal); 1374 } 1375 req.url(in.build()); 1376 req.data().clear(); // moved into url as get params 1377 } 1378 } 1379 1380 private static boolean needsMultipart(Connection.Request req) { 1381 // multipart mode, for files. add the header if we see something with an inputstream, and return a non-null boundary 1382 for (Connection.KeyVal keyVal : req.data()) { 1383 if (keyVal.hasInputStream()) 1384 return true; 1385 } 1386 return false; 1387 } 1388 1389 public static class KeyVal implements Connection.KeyVal { 1390 private String key; 1391 private String value; 1392 private @Nullable InputStream stream; 1393 private @Nullable String contentType; 1394 1395 public static KeyVal create(String key, String value) { 1396 return new KeyVal(key, value); 1397 } 1398 1399 public static KeyVal create(String key, String filename, InputStream stream) { 1400 return new KeyVal(key, filename) 1401 .inputStream(stream); 1402 } 1403 1404 private KeyVal(String key, String value) { 1405 Validate.notEmptyParam(key, "key"); 1406 Validate.notNullParam(value, "value"); 1407 this.key = key; 1408 this.value = value; 1409 } 1410 1411 @Override 1412 public KeyVal key(String key) { 1413 Validate.notEmptyParam(key, "key"); 1414 this.key = key; 1415 return this; 1416 } 1417 1418 @Override 1419 public String key() { 1420 return key; 1421 } 1422 1423 @Override 1424 public KeyVal value(String value) { 1425 Validate.notNullParam(value, "value"); 1426 this.value = value; 1427 return this; 1428 } 1429 1430 @Override 1431 public String value() { 1432 return value; 1433 } 1434 1435 @Override 1436 public KeyVal inputStream(InputStream inputStream) { 1437 Validate.notNullParam(inputStream, "inputStream"); 1438 this.stream = inputStream; 1439 return this; 1440 } 1441 1442 @Override @Nullable 1443 public InputStream inputStream() { 1444 return stream; 1445 } 1446 1447 @Override 1448 public boolean hasInputStream() { 1449 return stream != null; 1450 } 1451 1452 @Override 1453 public Connection.KeyVal contentType(String contentType) { 1454 Validate.notEmpty(contentType); 1455 this.contentType = contentType; 1456 return this; 1457 } 1458 1459 @Override @Nullable 1460 public String contentType() { 1461 return contentType; 1462 } 1463 1464 @Override 1465 public String toString() { 1466 return key + "=" + value; 1467 } 1468 } 1469}