001package org.jsoup;
002
003import org.jsoup.helper.RequestAuthenticator;
004import org.jsoup.nodes.Document;
005import org.jsoup.parser.Parser;
006import org.jsoup.parser.StreamParser;
007import org.jspecify.annotations.Nullable;
008
009import javax.net.ssl.SSLContext;
010import javax.net.ssl.SSLSocketFactory;
011import java.io.BufferedInputStream;
012import java.io.IOException;
013import java.io.InputStream;
014import java.io.UncheckedIOException;
015import java.net.Authenticator;
016import java.net.CookieStore;
017import java.net.Proxy;
018import java.net.URL;
019import java.util.Collection;
020import java.util.List;
021import java.util.Map;
022
023/**
024 The Connection interface is a convenient HTTP client and session object to fetch content from the web, and parse them
025 into Documents.
026 <p>To start a new session, use either {@link org.jsoup.Jsoup#newSession()} or {@link org.jsoup.Jsoup#connect(String)}.
027 Connections contain {@link Connection.Request} and {@link Connection.Response} objects (once executed). Configuration
028 settings (URL, timeout, useragent, etc) set on a session will be applied by default to each subsequent request.</p>
029 <p>To start a new request from the session, use {@link #newRequest()}.</p>
030 <p>Cookies are stored in memory for the duration of the session. For that reason, do not use one single session for all
031 requests in a long-lived application, or you are likely to run out of memory, unless care is taken to clean up the
032 cookie store. The cookie store for the session is available via {@link #cookieStore()}. You may provide your own
033 implementation via {@link #cookieStore(java.net.CookieStore)} before making requests.</p>
034 <p>Request configuration can be made using either the shortcut methods in Connection (e.g. {@link #userAgent(String)}),
035 or by methods in the {@link Connection.Request} object directly. All request configuration must be made before the request is
036 executed. When used as an ongoing session, initialize all defaults prior to making multi-threaded {@link
037#newRequest()}s.</p>
038 <p>Note that the term "Connection" used here does not mean that a long-lived connection is held against a server for
039 the lifetime of the Connection object. A socket connection is only made at the point of request execution ({@link
040#execute()}, {@link #get()}, or {@link #post()}), and the server's response consumed.</p>
041 <p>For multi-threaded implementations, it is important to use a {@link #newRequest()} for each request. The session may
042 be shared across concurrent threads, but a not a specific request.</p>
043 <p><b>HTTP/2</b> support: On JVM 11 and above, requests use {@link java.net.http.HttpClient}, which supports
044 HTTP/2. To use the legacy {@link java.net.HttpURLConnection} instead, set
045 <code>System.setProperty("jsoup.useHttpClient", "false")</code>.</p>
046 */
047@SuppressWarnings("unused")
048public interface Connection {
049
050    /**
051     * GET and POST http methods.
052     */
053    enum Method {
054        GET(false),
055        POST(true),
056        PUT(true),
057        DELETE(true),
058        /**
059         Note that unfortunately, PATCH is not supported in many JDKs.
060         */
061        PATCH(true),
062        HEAD(false),
063        OPTIONS(false),
064        TRACE(false);
065
066        private final boolean hasBody;
067
068        Method(boolean hasBody) {
069            this.hasBody = hasBody;
070        }
071
072        /**
073         * Check if this HTTP method has/needs a request body
074         * @return if body needed
075         */
076        public final boolean hasBody() {
077            return hasBody;
078        }
079    }
080
081    /**
082     Creates a new request, using this Connection as the session-state and to initialize the connection settings (which
083     may then be independently changed on the returned {@link Connection.Request} object).
084     @return a new Connection object, with a shared Cookie Store and initialized settings from this Connection and Request
085     @since 1.14.1
086     */
087    Connection newRequest();
088
089    /**
090     Creates a new request, using this Connection as the session-state and to initialize the connection settings (which
091     may then be independently changed on the returned {@link Connection.Request} object).
092     @return a new Connection object, with a shared Cookie Store and initialized settings from this Connection and Request
093     @param url URL for the new request
094     @since 1.17.1
095     */
096    default Connection newRequest(String url) {
097        return newRequest().url(url);
098    }
099
100    /**
101     Creates a new request, using this Connection as the session-state and to initialize the connection settings (which
102     may then be independently changed on the returned {@link Connection.Request} object).
103     @return a new Connection object, with a shared Cookie Store and initialized settings from this Connection and Request
104     @param url URL for the new request
105     @since 1.17.1
106     */
107    default Connection newRequest(URL url) {
108        return newRequest().url(url);
109    }
110
111    /**
112     * Set the request URL to fetch. The protocol must be HTTP or HTTPS.
113     * @param url URL to connect to
114     * @return this Connection, for chaining
115     */
116    Connection url(URL url);
117
118    /**
119     * Set the request URL to fetch. The protocol must be HTTP or HTTPS.
120     * @param url URL to connect to
121     * @return this Connection, for chaining
122     */
123    Connection url(String url);
124
125    /**
126     * Set the proxy to use for this request. Set to <code>null</code> to disable a previously set proxy.
127     * @param proxy proxy to use
128     * @return this Connection, for chaining
129     */
130    Connection proxy(@Nullable Proxy proxy);
131
132    /**
133     * Set the HTTP proxy to use for this request.
134     * @param host the proxy hostname
135     * @param port the proxy port
136     * @return this Connection, for chaining
137     */
138    Connection proxy(String host, int port);
139
140    /**
141     * Set the request user-agent header.
142     * @param userAgent user-agent to use
143     * @return this Connection, for chaining
144     * @see org.jsoup.helper.HttpConnection#DEFAULT_UA
145     */
146    Connection userAgent(String userAgent);
147
148    /**
149     Set the total maximum request duration. If a timeout occurs, an {@link java.net.SocketTimeoutException} will be
150     thrown.
151     <p>The default timeout is <b>30 seconds</b> (30,000 millis). A timeout of zero is treated as an infinite timeout.</p>
152     <p>This timeout specifies the combined maximum duration of the connection time and the time to read
153     the full response.</p>
154     <p>Implementation note: when this <code>Connection</code> is backed by <code>HttpURLConnection</code> (rather than <code>HttpClient</code>, as used in JVM 11+), this timeout is implemented by setting both the socket connect and read timeouts to half of the specified value.</p>
155
156     @param millis number of milliseconds (thousandths of a second) before timing out connects or reads.
157     @return this Connection, for chaining
158     @see #maxBodySize(int)
159     */
160    Connection timeout(int millis);
161
162    /**
163     * Set the maximum bytes to read from the (uncompressed) connection into the body, before the connection is closed,
164     * and the input truncated (i.e. the body content will be trimmed). <b>The default maximum is 2MB</b>. A max size of
165     * <code>0</code> is treated as an infinite amount (bounded only by your patience and the memory available on your
166     * machine).
167     *
168     * @param bytes number of bytes to read from the input before truncating
169     * @return this Connection, for chaining
170     */
171    Connection maxBodySize(int bytes);
172
173    /**
174     * Set the request referrer (aka "referer") header.
175     * @param referrer referrer to use
176     * @return this Connection, for chaining
177     */
178    Connection referrer(String referrer);
179
180    /**
181     * Configures the connection to (not) follow server redirects. By default, this is <b>true</b>.
182     * @param followRedirects true if server redirects should be followed.
183     * @return this Connection, for chaining
184     */
185    Connection followRedirects(boolean followRedirects);
186
187    /**
188     * Set the request method to use, GET or POST. Default is GET.
189     * @param method HTTP request method
190     * @return this Connection, for chaining
191     */
192    Connection method(Method method);
193
194    /**
195     * Configures the connection to not throw exceptions when an HTTP error occurs. (4xx - 5xx, e.g. 404 or 500). By
196     * default, this is <b>false</b>; an IOException is thrown if an error is encountered. If set to <b>true</b>, the
197     * response is populated with the error body, and the status message will reflect the error.
198     * @param ignoreHttpErrors - false (default) if HTTP errors should be ignored.
199     * @return this Connection, for chaining
200     */
201    Connection ignoreHttpErrors(boolean ignoreHttpErrors);
202
203    /**
204     * Ignore the document's Content-Type when parsing the response. By default, this is <b>false</b>, an unrecognised
205     * content-type will cause an IOException to be thrown. (This is to prevent producing garbage by attempting to parse
206     * a JPEG binary image, for example.) Set to true to force a parse attempt regardless of content type.
207     * @param ignoreContentType set to true if you would like the content type ignored on parsing the response into a
208     * Document.
209     * @return this Connection, for chaining
210     */
211    Connection ignoreContentType(boolean ignoreContentType);
212
213    /**
214     Set a custom SSL context for HTTPS connections.
215     <p>Note: when using the legacy <code>HttpURLConnection</code>, only the <code>SSLSocketFactory</code> from the
216     context will be used.</p>
217
218     @param sslContext SSL context
219     @return this Connection, for chaining
220     @since 1.21.2
221     */
222    default Connection sslContext(SSLContext sslContext) {
223        throw new UnsupportedOperationException();
224    }
225
226    /**
227     * Add a request data parameter. Request parameters are sent in the request query string for GETs, and in the
228     * request body for POSTs. A request may have multiple values of the same name.
229     * @param key data key
230     * @param value data value
231     * @return this Connection, for chaining
232     */
233    Connection data(String key, String value);
234
235    /**
236     * Add an input stream as a request data parameter. For GETs, has no effect, but for POSTS this will upload the
237     * input stream.
238     * <p>Use the {@link #data(String, String, InputStream, String)} method to set the uploaded file's mimetype.</p>
239     * @param key data key (form item name)
240     * @param filename the name of the file to present to the remove server. Typically just the name, not path,
241     * component.
242     * @param inputStream the input stream to upload, that you probably obtained from a {@link java.io.FileInputStream}.
243     * You must close the InputStream in a {@code finally} block.
244     * @return this Connection, for chaining
245     * @see #data(String, String, InputStream, String)
246     */
247    Connection data(String key, String filename, InputStream inputStream);
248
249    /**
250     * Add an input stream as a request data parameter. For GETs, has no effect, but for POSTS this will upload the
251     * input stream.
252     * @param key data key (form item name)
253     * @param filename the name of the file to present to the remove server. Typically just the name, not path,
254     * component.
255     * @param inputStream the input stream to upload, that you probably obtained from a {@link java.io.FileInputStream}.
256     * @param contentType the Content Type (aka mimetype) to specify for this file.
257     * You must close the InputStream in a {@code finally} block.
258     * @return this Connection, for chaining
259     */
260    Connection data(String key, String filename, InputStream inputStream, String contentType);
261
262    /**
263     * Adds all of the supplied data to the request data parameters
264     * @param data collection of data parameters
265     * @return this Connection, for chaining
266     */
267    Connection data(Collection<KeyVal> data);
268
269    /**
270     * Adds all of the supplied data to the request data parameters
271     * @param data map of data parameters
272     * @return this Connection, for chaining
273     */
274    Connection data(Map<String, String> data);
275
276    /**
277     Add one or more request {@code key, val} data parameter pairs.
278     <p>Multiple parameters may be set at once, e.g.:
279     <code>.data("name", "jsoup", "language", "Java", "language", "English");</code> creates a query string like:
280     <code>{@literal ?name=jsoup&language=Java&language=English}</code></p>
281     <p>For GET requests, data parameters will be sent on the request query string. For POST (and other methods that
282     contain a body), they will be sent as body form parameters, unless the body is explicitly set by
283     {@link #requestBody(String)}, in which case they will be query string parameters.</p>
284
285     @param keyvals a set of key value pairs.
286     @return this Connection, for chaining
287     */
288    Connection data(String... keyvals);
289
290    /**
291     * Get the data KeyVal for this key, if any
292     * @param key the data key
293     * @return null if not set
294     */
295    @Nullable KeyVal data(String key);
296
297    /**
298     * Set a POST (or PUT) request body. Useful when a server expects a plain request body (such as JSON), and not a set
299     * of URL encoded form key/value pairs. E.g.:
300     * <code><pre>Jsoup.connect(url)
301     * .requestBody(json)
302     * .header("Content-Type", "application/json")
303     * .post();</pre></code>
304     * If any data key/vals are supplied, they will be sent as URL query params.
305     * @see #requestBodyStream(InputStream)
306     * @return this Request, for chaining
307     */
308    Connection requestBody(String body);
309
310    /**
311     Set the request body. Useful for posting data such as byte arrays or files, and the server expects a single request
312     body (and not a multipart upload). E.g.:
313     <code><pre> Jsoup.connect(url)
314     .requestBody(new ByteArrayInputStream(bytes))
315     .header("Content-Type", "application/octet-stream")
316     .post();
317     </pre></code>
318     <p>Or, use a FileInputStream to data from disk.</p>
319     <p>You should close the stream in a finally block.</p>
320     <p>The stream is sent once and cannot be replayed. If a redirect or authentication challenge requires the request
321     to be resent, execution will fail; resend the request with a fresh stream.</p>
322
323     @param stream the input stream to send.
324     @return this Request, for chaining
325     @see #requestBody(String)
326     @since 1.20.1
327     */
328    default Connection requestBodyStream(InputStream stream) {
329        throw new UnsupportedOperationException();
330    }
331
332    /**
333     * Set a request header. Replaces any existing header with the same case-insensitive name.
334     * @param name header name
335     * @param value header value
336     * @return this Connection, for chaining
337     * @see org.jsoup.Connection.Request#header(String, String)
338     * @see org.jsoup.Connection.Request#headers()
339     */
340    Connection header(String name, String value);
341
342    /**
343     * Sets each of the supplied headers on the request. Existing headers with the same case-insensitive name will be
344     * replaced with the new value.
345     * @param headers map of headers name {@literal ->} value pairs
346     * @return this Connection, for chaining
347     * @see org.jsoup.Connection.Request#headers()
348     */
349    Connection headers(Map<String,String> headers);
350
351    /**
352     * Set a cookie to be sent in the request.
353     * @param name name of cookie
354     * @param value value of cookie
355     * @return this Connection, for chaining
356     */
357    Connection cookie(String name, String value);
358
359    /**
360     * Adds each of the supplied cookies to the request.
361     * @param cookies map of cookie name {@literal ->} value pairs
362     * @return this Connection, for chaining
363     */
364    Connection cookies(Map<String, String> cookies);
365
366    /**
367     Provide a custom or pre-filled CookieStore to be used on requests made by this Connection.
368     @param cookieStore a cookie store to use for subsequent requests
369     @return this Connection, for chaining
370     @since 1.14.1
371     */
372    Connection cookieStore(CookieStore cookieStore);
373
374    /**
375     Get the cookie store used by this Connection.
376     @return the cookie store
377     @since 1.14.1
378     */
379    CookieStore cookieStore();
380
381    /**
382     * Provide a specific parser to use when parsing the response to a Document. If not set, jsoup defaults to the
383     * {@link Parser#htmlParser() HTML parser}, unless the response content-type is XML, in which case the
384     * {@link Parser#xmlParser() XML parser} is used.
385     * @param parser alternate parser
386     * @return this Connection, for chaining
387     */
388    Connection parser(Parser parser);
389
390    /**
391     * Set the character-set used to encode the request body. Defaults to {@code UTF-8}.
392     * @param charset character set to encode the request body
393     * @return this Connection, for chaining
394     */
395    Connection postDataCharset(String charset);
396
397    /**
398     Set the authenticator to use for this connection, enabling requests to URLs, and via proxies, that require
399     authentication credentials.
400     <p>The authentication scheme used is automatically detected during the request execution.
401     Supported schemes (subject to the platform) are {@code basic}, {@code digest}, {@code NTLM},
402     and {@code Kerberos}.</p>
403
404     <p>To use, supply a {@link RequestAuthenticator} function that:
405     <ol>
406     <li>validates the URL that is requesting authentication, and</li>
407     <li>returns the appropriate credentials (username and password)</li>
408     </ol>
409     </p>
410
411     <p>For example, to authenticate both to a proxy and a downstream web server:
412     <code><pre>
413     Connection session = Jsoup.newSession()
414         .proxy("proxy.example.com", 8080)
415         .auth(auth -&gt; {
416             if (auth.isServer()) { // provide credentials for the request url
417                 Validate.isTrue(auth.url().getHost().equals("example.com"));
418                 // check that we're sending credentials were we expect, and not redirected out
419                 return auth.credentials("username", "password");
420             } else { // auth.isProxy()
421                 return auth.credentials("proxy-user", "proxy-password");
422             }
423         });
424
425     Connection.Response response = session.newRequest("https://example.com/adminzone/").execute();
426     </pre></code>
427     </p>
428
429     <p>The system may cache the authentication and use it for subsequent requests to the same resource.</p>
430
431     <p><b>Implementation notes</b></p>
432     <p>For compatibility, on a Java 8 platform, authentication is set up via the system-wide default
433     {@link java.net.Authenticator#setDefault(Authenticator)} method via a ThreadLocal delegator. Whilst the
434     authenticator used is request specific and thread-safe, if you have other calls to {@code setDefault}, they will be
435     incompatible with this implementation.</p>
436     <p>On Java 9 and above, the preceding note does not apply; authenticators are directly set on the request. </p>
437     <p>If you are attempting to authenticate to a proxy that uses the {@code basic} scheme and will be fetching HTTPS
438     URLs, you need to configure your Java platform to enable that, by setting the
439     {@code jdk.http.auth.tunneling.disabledSchemes} system property to {@code ""}.
440     This must be executed prior to any authorization attempts. E.g.:
441     <code><pre>
442     static {
443        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
444        // removes Basic, which is otherwise excluded from auth for CONNECT tunnels
445     }</pre></code>
446     </p>
447     * @param authenticator the authenticator to use in this connection
448     * @return this Connection, for chaining
449     * @since 1.17.1
450     */
451    default Connection auth(@Nullable RequestAuthenticator authenticator) {
452        throw new UnsupportedOperationException();
453    }
454
455    /**
456     * Execute the request as a GET, and parse the result.
457     * @return parsed Document
458     * @throws java.net.MalformedURLException if the request URL is not an HTTP or HTTPS URL, or is otherwise malformed
459     * @throws HttpStatusException if the response is not OK and HTTP response errors are not ignored
460     * @throws UnsupportedMimeTypeException if the response mime type is not supported and those errors are not ignored
461     * @throws java.net.SocketTimeoutException if the connection times out
462     * @throws IOException on error
463     */
464    Document get() throws IOException;
465
466    /**
467     * Execute the request as a POST, and parse the result.
468     * @return parsed Document
469     * @throws java.net.MalformedURLException if the request URL is not a HTTP or HTTPS URL, or is otherwise malformed
470     * @throws HttpStatusException if the response is not OK and HTTP response errors are not ignored
471     * @throws UnsupportedMimeTypeException if the response mime type is not supported and those errors are not ignored
472     * @throws java.net.SocketTimeoutException if the connection times out
473     * @throws IOException on error
474     */
475    Document post() throws IOException;
476
477    /**
478     * Execute the request.
479     * @return the executed {@link Response}
480     * @throws java.net.MalformedURLException if the request URL is not a HTTP or HTTPS URL, or is otherwise malformed
481     * @throws HttpStatusException if the response is not OK and HTTP response errors are not ignored
482     * @throws UnsupportedMimeTypeException if the response mime type is not supported and those errors are not ignored
483     * @throws java.net.SocketTimeoutException if the connection times out
484     * @throws IOException on error
485     */
486    Response execute() throws IOException;
487
488    /**
489     * Get the request object associated with this connection
490     * @return request
491     */
492    Request request();
493
494    /**
495     * Set the connection's request
496     * @param request new request object
497     * @return this Connection, for chaining
498     */
499    Connection request(Request request);
500
501    /**
502     * Get the response, once the request has been executed.
503     * @return response
504     * @throws IllegalArgumentException if called before the response has been executed.
505     */
506    Response response();
507
508    /**
509     * Set the connection's response
510     * @param response new response
511     * @return this Connection, for chaining
512     */
513    Connection response(Response response);
514
515    /**
516     Set the response progress handler, which will be called periodically as the response body is downloaded. Since
517     documents are parsed as they are downloaded, this is also a good proxy for the parse progress.
518     <p>The Response object is supplied as the progress context, and may be read from to obtain headers etc.</p>
519     @param handler the progress handler
520     @return this Connection, for chaining
521     @since 1.18.1
522     */
523    default Connection onResponseProgress(Progress<Response> handler) {
524        throw new UnsupportedOperationException();
525    }
526
527    /**
528     * Common methods for Requests and Responses
529     * @param <T> Type of Base, either Request or Response
530     */
531    @SuppressWarnings("UnusedReturnValue")
532    interface Base<T extends Base<T>> {
533        /**
534         * Get the URL of this Request or Response. For redirected responses, this will be the final destination URL.
535         * @return URL
536         * @throws IllegalArgumentException if called on a Request that was created without a URL.
537         */
538        URL url();
539
540        /**
541         * Set the URL
542         * @param url new URL
543         * @return this, for chaining
544         */
545        T url(URL url);
546
547        /**
548         * Get the request method, which defaults to <code>GET</code>
549         * @return method
550         */
551        Method method();
552
553        /**
554         * Set the request method
555         * @param method new method
556         * @return this, for chaining
557         */
558        T method(Method method);
559
560        /**
561         * Get the value of a header. If there is more than one header value with the same name, the headers are returned
562         * comma separated, per <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">rfc2616-sec4</a>.
563         * <p>
564         * Header names are case-insensitive.
565         * </p>
566         * @param name name of header (case-insensitive)
567         * @return value of header, or null if not set.
568         * @see #hasHeader(String)
569         * @see #cookie(String)
570         */
571        @Nullable String header(String name);
572
573        /**
574         * Get the values of a header.
575         * @param name header name, case-insensitive.
576         * @return a list of values for this header, or an empty list if not set.
577         */
578        List<String> headers(String name);
579
580        /**
581         * Set a header. This method will overwrite any existing header with the same case-insensitive name. If there
582         * is more than one value for this header, this method will update the first matching header.
583         * <p>For compatibility, if the content of the header includes text that cannot be represented by ISO-8859-1,
584         * then it should be encoded first per <a href="https://www.ietf.org/rfc/rfc2047.txt">RFC 2047</a>.</p>
585         * @param name Name of header
586         * @param value Value of header
587         * @return this, for chaining
588         * @see #addHeader(String, String)
589         */
590        T header(String name, String value);
591
592        /**
593         * Add a header. The header will be added regardless of whether a header with the same name already exists.
594         * <p>For compatibility, if the content of the header includes text that cannot be represented by ISO-8859-1,
595         * then it should be encoded first per <a href="https://www.ietf.org/rfc/rfc2047.txt">RFC 2047</a>.</p>
596         * @param name Name of new header
597         * @param value Value of new header
598         * @return this, for chaining
599         */
600        T addHeader(String name, String value);
601
602        /**
603         * Check if a header is present
604         * @param name name of header (case-insensitive)
605         * @return if the header is present in this request/response
606         */
607        boolean hasHeader(String name);
608
609        /**
610         * Check if a header is present, with the given value
611         * @param name header name (case-insensitive)
612         * @param value value (case-insensitive)
613         * @return if the header and value pair are set in this req/res
614         */
615        boolean hasHeaderWithValue(String name, String value);
616
617        /**
618         * Remove headers by name. If there is more than one header with this name, they will all be removed.
619         * @param name name of header to remove (case-insensitive)
620         * @return this, for chaining
621         */
622        T removeHeader(String name);
623
624        /**
625         * Retrieve all of the request/response header names and corresponding values as a map. For headers with multiple
626         * values, only the first header is returned.
627         * <p>Note that this is a view of the headers only, and changes made to this map will not be reflected in the
628         * request/response object.</p>
629         * @return headers
630         * @see #multiHeaders()
631
632         */
633        Map<String, String> headers();
634
635        /**
636         * Retreive all of the headers, keyed by the header name, and with a list of values per header.
637         * @return a list of multiple values per header.
638         */
639        Map<String, List<String>> multiHeaders();
640
641        /**
642         * Get a cookie value by name from this request/response.
643         * @param name name of cookie to retrieve.
644         * @return value of cookie, or null if not set
645         */
646        @Nullable String cookie(String name);
647
648        /**
649         * Set a cookie in this request/response.
650         * @param name name of cookie
651         * @param value value of cookie
652         * @return this, for chaining
653         */
654        T cookie(String name, String value);
655
656        /**
657         * Check if a cookie is present
658         * @param name name of cookie
659         * @return if the cookie is present in this request/response
660         */
661        boolean hasCookie(String name);
662
663        /**
664         * Remove a cookie by name
665         * @param name name of cookie to remove
666         * @return this, for chaining
667         */
668        T removeCookie(String name);
669
670        /**
671         Retrieve the request/response cookies as a map. For response cookies, if duplicate cookie names were sent, the
672         last one set will be the one included. For session management, rather than using these response cookies, prefer
673         to use {@link Jsoup#newSession()} and related methods.
674
675         @return simple cookie map
676         @see #cookieStore()
677         */
678        Map<String, String> cookies();
679    }
680
681    /**
682     * Represents a HTTP request.
683     */
684    @SuppressWarnings("UnusedReturnValue")
685    interface Request extends Base<Request> {
686        /**
687         * Get the proxy used for this request.
688         * @return the proxy; <code>null</code> if not enabled.
689         */
690        @Nullable Proxy proxy();
691
692        /**
693         * Update the proxy for this request.
694         * @param proxy the proxy ot use; <code>null</code> to disable.
695         * @return this Request, for chaining
696         */
697        Request proxy(@Nullable Proxy proxy);
698
699        /**
700         * Set the HTTP proxy to use for this request.
701         * @param host the proxy hostname
702         * @param port the proxy port
703         * @return this Connection, for chaining
704         */
705        Request proxy(String host, int port);
706
707        /**
708         * Get the request timeout, in milliseconds.
709         * @return the timeout in milliseconds.
710         */
711        int timeout();
712
713        /**
714         * Update the request timeout.
715         * @param millis timeout, in milliseconds
716         * @return this Request, for chaining
717         */
718        Request timeout(int millis);
719
720        /**
721         * Get the maximum body size, in bytes.
722         * @return the maximum body size, in bytes.
723         */
724        int maxBodySize();
725
726        /**
727         * Update the maximum body size, in bytes.
728         * @param bytes maximum body size, in bytes.
729         * @return this Request, for chaining
730         */
731        Request maxBodySize(int bytes);
732
733        /**
734         * Get the current followRedirects configuration.
735         * @return true if followRedirects is enabled.
736         */
737        boolean followRedirects();
738
739        /**
740         * Configures the request to (not) follow server redirects. By default this is <b>true</b>.
741         * @param followRedirects true if server redirects should be followed.
742         * @return this Request, for chaining
743         */
744        Request followRedirects(boolean followRedirects);
745
746        /**
747         * Get the current ignoreHttpErrors configuration.
748         * @return true if errors will be ignored; false (default) if HTTP errors will cause an IOException to be
749         * thrown.
750         */
751        boolean ignoreHttpErrors();
752
753        /**
754         * Configures the request to ignore HTTP errors in the response.
755         * @param ignoreHttpErrors set to true to ignore HTTP errors.
756         * @return this Request, for chaining
757         */
758        Request ignoreHttpErrors(boolean ignoreHttpErrors);
759
760        /**
761         * Get the current ignoreContentType configuration.
762         * @return true if invalid content-types will be ignored; false (default) if they will cause an IOException to
763         * be thrown.
764         */
765        boolean ignoreContentType();
766
767        /**
768         * Configures the request to ignore the Content-Type of the response.
769         * @param ignoreContentType set to true to ignore the content type.
770         * @return this Request, for chaining
771         */
772        Request ignoreContentType(boolean ignoreContentType);
773
774        /**
775         * Get the current custom SSL socket factory, if any.
776         * @return custom SSL socket factory if set, null otherwise
777         */
778        @Nullable SSLSocketFactory sslSocketFactory();
779
780        /**
781         Get the current custom SSL context, if any.
782
783         @return custom SSL context if set, null otherwise
784         @since 1.21.2
785         */
786        @Nullable
787        default SSLContext sslContext() {
788            throw new UnsupportedOperationException();
789        }
790
791        /**
792         Set a custom SSL context for HTTPS connections.
793         <p>Note: when using the legacy <code>HttpURLConnection</code>, only the <code>SSLSocketFactory</code> from the
794         context will be used.</p>
795
796         @param sslContext SSL context
797         @return this Request, for chaining
798         @since 1.21.2
799         */
800        default Request sslContext(SSLContext sslContext) {
801            throw new UnsupportedOperationException();
802        }
803
804        /**
805         * Add a data parameter to the request
806         * @param keyval data to add.
807         * @return this Request, for chaining
808         */
809        Request data(KeyVal keyval);
810
811        /**
812         * Get all of the request's data parameters
813         * @return collection of keyvals
814         */
815        Collection<KeyVal> data();
816
817        /**
818         * Set a POST (or PUT) request body. Useful when a server expects a plain request body, not a set of URL
819         * encoded form key/value pairs. E.g.:
820         * <code><pre>Jsoup.connect(url)
821         * .requestBody(json)
822         * .header("Content-Type", "application/json")
823         * .post();</pre></code>
824         * <p>If any data key/vals are supplied, they will be sent as URL query params.</p>
825         * @param body to use as the request body. Set to null to clear a previously set body.
826         * @return this Request, for chaining
827         * @see #requestBodyStream(InputStream)
828         */
829        Request requestBody(@Nullable String body);
830
831        /**
832         * Get the current request body.
833         * @return null if not set.
834         */
835        @Nullable String requestBody();
836
837        /**
838         Set the request body. Useful for posting data such as byte arrays or files, and the server expects a single
839         request body (and not a multipart upload). E.g.:
840         <code><pre> Jsoup.connect(url)
841         .requestBody(new ByteArrayInputStream(bytes))
842         .header("Content-Type", "application/octet-stream")
843         .post();
844         </pre></code>
845         <p>Or, use a FileInputStream to data from disk.</p>
846         <p>You should close the stream in a finally block.</p>
847         <p>The stream is sent once and cannot be replayed. If a redirect or authentication challenge requires the
848         request to be resent, execution will fail; resend the request with a fresh stream.</p>
849
850         @param stream the input stream to send.
851         @return this Request, for chaining
852         @see #requestBody(String)
853         @since 1.20.1
854         */
855        default Request requestBodyStream(InputStream stream) {
856            throw new UnsupportedOperationException();
857        }
858
859        /**
860         * Specify the parser to use when parsing the document.
861         * @param parser parser to use.
862         * @return this Request, for chaining
863         */
864        Request parser(Parser parser);
865
866        /**
867         * Get the current parser to use when parsing the document.
868         * @return current Parser
869         */
870        Parser parser();
871
872        /**
873         * Sets the post data character set for x-www-form-urlencoded post data
874         * @param charset character set to encode post data
875         * @return this Request, for chaining
876         */
877        Request postDataCharset(String charset);
878
879        /**
880         * Gets the post data character set for x-www-form-urlencoded post data
881         * @return character set to encode post data
882         */
883        String postDataCharset();
884
885        /**
886         Set the authenticator to use for this request.
887         See {@link Connection#auth(RequestAuthenticator) Connection.auth(authenticator)} for examples and
888         implementation notes.
889         * @param authenticator the authenticator
890         * @return this Request, for chaining.
891         * @since 1.17.1
892         */
893        default Request auth(@Nullable RequestAuthenticator authenticator)  {
894            throw new UnsupportedOperationException();
895        }
896
897        /**
898         Get the RequestAuthenticator, if any, that will be used on this request.
899         * @return the RequestAuthenticator, or {@code null} if not set
900         * @since 1.17.1
901         */
902        @Nullable
903        default RequestAuthenticator auth() {
904            throw new UnsupportedOperationException();
905        }
906    }
907
908    /**
909     * Represents a HTTP response.
910     */
911    interface Response extends Base<Response> {
912
913        /**
914         * Get the status code of the response.
915         * @return status code
916         */
917        int statusCode();
918
919        /**
920         * Get the status message of the response.
921         * @return status message
922         */
923        String statusMessage();
924
925        /**
926         * Get the character set name of the response, derived from the content-type header.
927         * @return character set name if set, <b>null</b> if not
928         */
929        @Nullable String charset();
930
931        /**
932         * Set / override the response character set. When the document body is parsed it will be with this charset.
933         * @param charset to decode body as
934         * @return this Response, for chaining
935         */
936        Response charset(String charset);
937
938        /**
939         * Get the response content type (e.g. "text/html");
940         * @return the response content type, or <b>null</b> if one was not set
941         */
942        @Nullable String contentType();
943
944        /**
945         Read and parse the body of the response as a Document. If you intend to parse the same response multiple times,
946         you should {@link #readFully()} first, which will buffer the body into memory.
947
948         @return a parsed Document
949         @throws IOException if an IO exception occurs whilst reading the body.
950         @see #readFully()
951         */
952        Document parse() throws IOException;
953
954        /**
955         Read the response body, and returns it as a plain String.
956
957         @return body
958         @throws IOException if an IO exception occurs whilst reading the body.
959         @since 1.21.1
960         */
961        default String readBody() throws IOException {
962            throw new UnsupportedOperationException();
963        }
964
965        /**
966         Get the body of the response as a plain String.
967
968         <p>Will throw an UncheckedIOException if the body has not been buffered and an error occurs whilst reading the
969         body; use {@link #readFully()} first to buffer the body and catch any exceptions explicitly. Or more simply,
970         {@link #readBody()}.</p>
971
972         @return body
973         @throws UncheckedIOException if an IO exception occurs whilst reading the body.
974         @see #readBody()
975         @see #readFully()
976         */
977        String body();
978
979        /**
980         Get the body of the response as an array of bytes.
981
982         <p>Will throw an UncheckedIOException if the body has not been buffered and an error occurs whilst reading the
983         body; use {@link #readFully()} first to buffer the body and catch any exceptions explicitly.</p>
984
985         @return body bytes
986         @throws UncheckedIOException if an IO exception occurs whilst reading the body.
987         @see #readFully()
988         */
989        byte[] bodyAsBytes();
990
991        /**
992         Read the body of the response into a local buffer, so that {@link #parse()} may be called repeatedly on the same
993         connection response. Otherwise, once the response is read, its InputStream will have been drained and may not be
994         re-read.
995
996         <p>Subsequent calls methods than consume the body, such as {@link #parse()}, {@link #body()},
997         {@link #bodyAsBytes()}, will not need to read the body again, and will not throw exceptions.</p>
998         <p>Calling {@link #readBody()}} has the same effect.</p>
999
1000         @return this response, for chaining
1001         @throws IOException if an IO exception occurs during buffering.
1002         @since 1.21.1
1003         */
1004        default Response readFully() throws IOException {
1005            throw new UnsupportedOperationException();
1006        }
1007
1008        /**
1009         Tests whether the response body was truncated because it exceeded the configured {@link Request#maxBodySize()}.
1010         <p>The result is authoritative once the body has been consumed by {@link #parse()}, {@link #readFully()}, or
1011         {@link #bodyStream()} through end of stream. Before then, a {@code false} result is provisional.</p>
1012         @return true if decoded response content was omitted
1013         @since 1.24.1
1014         */
1015        default boolean isTruncated() {
1016            return false;
1017        }
1018
1019        /**
1020         Get the body of the response as a (buffered) InputStream. You should close the input stream when you're done
1021         with it.
1022         <p>Other body methods (like readFully, body, parse, etc) will generally not work in conjunction with this method,
1023         as it consumes the InputStream.</p>
1024         <p>The configured maximum body size and request timeout apply to this stream. Set {@link #maxBodySize(int)} to
1025         {@code 0} for an unlimited body size.</p>
1026         <p>This method is useful for writing large responses to disk, without buffering them completely into memory
1027         first.</p>
1028         @return the response body input stream
1029         */
1030        BufferedInputStream bodyStream();
1031
1032        /**
1033         Returns a {@link StreamParser} that will parse the Response progressively.
1034         * @return a StreamParser, prepared to parse this response.
1035         * @throws IOException if an IO exception occurs preparing the parser.
1036         */
1037        default StreamParser streamParser() throws IOException {
1038            throw new UnsupportedOperationException();
1039        }
1040    }
1041
1042    /**
1043     * A Key:Value tuple(+), used for form data.
1044     */
1045    interface KeyVal {
1046
1047        /**
1048         * Update the key of a keyval
1049         * @param key new key
1050         * @return this KeyVal, for chaining
1051         */
1052        KeyVal key(String key);
1053
1054        /**
1055         * Get the key of a keyval
1056         * @return the key
1057         */
1058        String key();
1059
1060        /**
1061         * Update the value of a keyval
1062         * @param value the new value
1063         * @return this KeyVal, for chaining
1064         */
1065        KeyVal value(String value);
1066
1067        /**
1068         * Get the value of a keyval
1069         * @return the value
1070         */
1071        String value();
1072
1073        /**
1074         * Add or update an input stream to this keyVal
1075         * @param inputStream new input stream
1076         * @return this KeyVal, for chaining
1077         */
1078        KeyVal inputStream(InputStream inputStream);
1079
1080        /**
1081         * Get the input stream associated with this keyval, if any
1082         * @return input stream if set, or null
1083         */
1084        @Nullable InputStream inputStream();
1085
1086        /**
1087         * Does this keyval have an input stream?
1088         * @return true if this keyval does indeed have an input stream
1089         */
1090        boolean hasInputStream();
1091
1092        /**
1093         * Set the Content Type header used in the MIME body (aka mimetype) when uploading files.
1094         * Only useful if {@link #inputStream(InputStream)} is set.
1095         * <p>Will default to {@code application/octet-stream}.</p>
1096         * @param contentType the new content type
1097         * @return this KeyVal
1098         */
1099        KeyVal contentType(String contentType);
1100
1101        /**
1102         * Get the current Content Type, or {@code null} if not set.
1103         * @return the current Content Type.
1104         */
1105        @Nullable String contentType();
1106    }
1107}