View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit;
16  
17  import java.io.IOException;
18  import java.io.ObjectInputStream;
19  import java.io.ObjectOutputStream;
20  import java.io.Serializable;
21  import java.net.IDN;
22  import java.net.MalformedURLException;
23  import java.net.URL;
24  import java.nio.charset.Charset;
25  import java.nio.charset.StandardCharsets;
26  import java.util.ArrayList;
27  import java.util.Collections;
28  import java.util.EnumSet;
29  import java.util.HashMap;
30  import java.util.List;
31  import java.util.Map;
32  import java.util.Set;
33  import java.util.function.Predicate;
34  import java.util.function.UnaryOperator;
35  
36  import org.apache.http.auth.Credentials;
37  import org.htmlunit.http.HttpUtils;
38  import org.htmlunit.httpclient.HtmlUnitUsernamePasswordCredentials;
39  import org.htmlunit.util.NameValuePair;
40  import org.htmlunit.util.StringUtils;
41  import org.htmlunit.util.UrlUtils;
42  
43  /**
44   * Parameter object for making web requests.
45   *
46   * @author Brad Clarke
47   * @author Hans Donner
48   * @author Ahmed Ashour
49   * @author Marc Guillemot
50   * @author Rodney Gitzel
51   * @author Ronald Brill
52   * @author Adam Afeltowicz
53   * @author Joerg Werner
54   * @author Michael Lueck
55   * @author Lai Quang Duong
56   * @author Kristof Neirynck
57   * @author Vidya m
58   */
59  @SuppressWarnings("PMD.TooManyFields")
60  public class WebRequest implements Serializable {
61  
62      /**
63       * Enum to configure request creation.
64       */
65      public enum HttpHint {
66          /** Force to include the charset. */
67          IncludeCharsetInContentTypeHeader,
68  
69          /** Disable sending of stored cookies and receiving of new cookies. */
70          BlockCookies,
71  
72          /** Do not follow redirects; the response of the redirect is returned as it is. */
73          DoNotFollowRedirects
74      }
75  
76      /**
77       * The destination of a request, as defined by the Fetch spec
78       * (<a href="https://fetch.spec.whatwg.org/#concept-request-destination">
79       * https://fetch.spec.whatwg.org/#concept-request-destination</a>).
80       * <p>
81       * This is used to compute the value of the {@code Sec-Fetch-Dest} request
82       * header (see <a href="https://www.w3.org/TR/fetch-metadata/">
83       * https://www.w3.org/TR/fetch-metadata/</a>) and also determines the default
84       * {@link FetchMode} to be used, unless explicitly overridden via
85       * {@link #setFetchModeOverride(FetchMode)}.
86       * </p>
87       */
88      public enum FetchDestination {
89          /** A top-level document, e.g. loaded by the address bar, a link, or a form submission. */
90          DOCUMENT("document"),
91          /** A nested browsing context of type {@code <iframe>}. */
92          IFRAME("iframe"),
93          /** A nested browsing context of type {@code <frame>}. */
94          FRAME("frame"),
95          /** An {@code <object>} element. */
96          OBJECT("object"),
97          /** An {@code <embed>} element. */
98          EMBED("embed"),
99          /** An image, e.g. {@code <img>}, a CSS background-image, or a favicon. */
100         IMAGE("image"),
101         /** A classic or module script, e.g. {@code <script src>}. */
102         SCRIPT("script"),
103         /** A stylesheet, e.g. {@code <link rel=stylesheet>} or a CSS {@code @import}. */
104         STYLE("style"),
105         /** A font resource, e.g. loaded via {@code @font-face}. */
106         FONT("font"),
107         /** An {@code <audio>} resource. */
108         AUDIO("audio"),
109         /** A {@code <video>} resource. */
110         VIDEO("video"),
111         /** A {@code <track>} resource. */
112         TRACK("track"),
113         /** A dedicated worker script. */
114         WORKER("worker"),
115         /** A shared worker script. */
116         SHARED_WORKER("sharedworker"),
117         /** A service worker script. */
118         SERVICE_WORKER("serviceworker"),
119         /** A web app manifest, e.g. {@code <link rel=manifest>}. */
120         MANIFEST("manifest"),
121         /** A reporting endpoint request. */
122         REPORT("report"),
123         /** A WebSocket handshake request. */
124         WEBSOCKET("websocket"),
125         /** No specific destination, e.g. {@code XMLHttpRequest} or {@code fetch()}. */
126         EMPTY("empty");
127 
128         private final String value_;
129 
130         FetchDestination(final String value) {
131             value_ = value;
132         }
133 
134         /**
135          * Returns the value to be used for the {@code Sec-Fetch-Dest} header.
136          *
137          * @return the value to be used for the {@code Sec-Fetch-Dest} header
138          */
139         public String getValue() {
140             return value_;
141         }
142     }
143 
144     /**
145      * The cache mode of a request, as defined by the Fetch spec; used by {@code fetch()}.
146      *
147      * @see <a href="https://fetch.spec.whatwg.org/#concept-request-cache-mode">Fetch Standard - cache mode</a>
148      */
149     public enum CacheMode {
150         /** Use the cache like the browser does it for normal requests. */
151         DEFAULT,
152         /** Do not use the cache: no lookup and the response is not stored. */
153         NO_STORE,
154         /** No lookup in the cache, but the response is stored. */
155         RELOAD,
156         /** A cached response is always validated with a conditional request. */
157         NO_CACHE,
158         /** A cached response is used also if it is stale. */
159         FORCE_CACHE,
160         /** Only a cached response (also a stale one) is used; without one this is a network error. */
161         ONLY_IF_CACHED
162     }
163 
164     /**
165      * The mode of a request, as defined by the Fetch spec
166      * (<a href="https://fetch.spec.whatwg.org/#concept-request-mode">
167      * https://fetch.spec.whatwg.org/#concept-request-mode</a>).
168      * <p>
169      * This is used to compute the value of the {@code Sec-Fetch-Mode} request
170      * header. Most {@link FetchDestination}s imply a fixed mode; this only needs
171      * to be set explicitly to override that default - e.g. for a {@code fetch()}
172      * call using an explicit {@code mode} option, or a subresource request using
173      * the {@code crossorigin} attribute.
174      * </p>
175      */
176     public enum FetchMode {
177         /** Same-origin requests, e.g. worker scripts, or {@code fetch()} with {@code mode: 'same-origin'}. */
178         SAME_ORIGIN("same-origin"),
179         /** Subresource requests without CORS, e.g. {@code <img>} without {@code crossorigin}. */
180         NO_CORS("no-cors"),
181         /** CORS-enabled requests, e.g. {@code XMLHttpRequest}, {@code fetch()} default, or module scripts. */
182         CORS("cors"),
183         /** Navigations, e.g. top-level document loads, {@code <iframe>}/{@code <frame>} loads. */
184         NAVIGATE("navigate"),
185         /** WebSocket handshake requests. */
186         WEBSOCKET("websocket");
187 
188         private final String value_;
189 
190         FetchMode(final String value) {
191             value_ = value;
192         }
193 
194         /**
195          * Returns the value to be used for the {@code Sec-Fetch-Mode} header.
196          *
197          * @return the value to be used for the {@code Sec-Fetch-Mode} header
198          */
199         public String getValue() {
200             return value_;
201         }
202     }
203 
204     // String instead of java.net.URL because "about:blank" URLs don't serialize correctly
205     private String url_;
206 
207     private String proxyHost_;
208     private int proxyPort_;
209     private String proxyScheme_;
210     private boolean isSocksProxy_;
211     private HttpMethod httpMethod_ = HttpMethod.GET;
212     private FormEncodingType encodingType_ = FormEncodingType.URL_ENCODED;
213     private Map<String, String> additionalHeaders_ = new HashMap<>();
214     private Credentials urlCredentials_;
215     private Credentials credentials_;
216     private int timeout_;
217     private transient Set<HttpHint> httpHints_;
218 
219     private transient Charset charset_ = StandardCharsets.ISO_8859_1;
220     // https://datatracker.ietf.org/doc/html/rfc6838#section-4.2.1
221     // private transient Charset defaultResponseContentCharset_ = StandardCharsets.UTF_8;
222     private transient Charset defaultResponseContentCharset_ = StandardCharsets.ISO_8859_1;
223 
224     /*
225      * These two are mutually exclusive; additionally, requestBody_ should only be
226      * set for POST requests.
227      */
228     private List<NameValuePair> requestParameters_ = Collections.emptyList();
229     private String requestBody_;
230 
231     // Sec-Fetch-* support; see https://www.w3.org/TR/fetch-metadata/
232     private FetchDestination fetchDestination_ = FetchDestination.EMPTY;
233     private FetchMode fetchModeOverride_;
234     private boolean userActivation_;
235     private CacheMode cacheMode_ = CacheMode.DEFAULT;
236 
237     // String instead of java.net.URL for the same serialization reason as url_ above;
238     // null means "no initiator" (e.g. a browser-chrome-initiated navigation), which
239     // maps to Sec-Fetch-Site: none.
240     private String requestingUrl_;
241     // the full referrer (without user info and ref) and the policy used to determine the Referer header
242     private String referrer_;
243     private ReferrerPolicy referrerPolicy_;
244     private String siteForCookies_;
245 
246     // e.g. the CSP form-action check
247     private transient Predicate<URL> redirectFilter_;
248     private transient UnaryOperator<URL> redirectUrlMapper_;
249 
250     /**
251      * Instantiates a {@link WebRequest} for the specified URL,
252      * setting the Accept and Accept-Encoding headers if provided.
253      *
254      * @param url                  the target URL
255      * @param acceptHeader         the accept header to use
256      * @param acceptEncodingHeader the accept encoding header to use
257      */
258     public WebRequest(final URL url, final String acceptHeader, final String acceptEncodingHeader) {
259         setUrl(url);
260         if (acceptHeader != null) {
261             setAdditionalHeader(HttpHeader.ACCEPT, acceptHeader);
262         }
263         if (acceptEncodingHeader != null) {
264             setAdditionalHeader(HttpHeader.ACCEPT_ENCODING, acceptEncodingHeader);
265         }
266         timeout_ = -1;
267 
268         // for backward compatibility
269         setFetchDestination(FetchDestination.DOCUMENT);
270         setFetchModeOverride(FetchMode.NAVIGATE);
271         setUserActivation(true);
272     }
273 
274     /**
275      * Instantiates a {@link WebRequest} for the specified URL,
276      * using the given charset and referer.
277      *
278      * @param url        the target URL
279      * @param charset    the charset to use
280      * @param refererUrl the url be used by the referer header
281      */
282     public WebRequest(final URL url, final Charset charset, final URL refererUrl) {
283         setUrl(url);
284         setCharset(charset);
285         setRefererHeader(refererUrl);
286     }
287 
288     /**
289      * Returns a new request for about:blank.
290      *
291      * @return a new request for about:blank
292      */
293     public static WebRequest newAboutBlankRequest() {
294         return new WebRequest(UrlUtils.URL_ABOUT_BLANK, "*/*", "gzip, deflate");
295     }
296 
297     /**
298      * Instantiates a {@link WebRequest} for the specified URL.
299      *
300      * @param url the target URL
301      */
302     public WebRequest(final URL url) {
303         this(url, "*/*", "gzip, deflate");
304     }
305 
306     /**
307      * Instantiates a {@link WebRequest} for the specified URL
308      * using the given HTTP submit method.
309      *
310      * @param url          the target URL
311      * @param submitMethod the HTTP submit method to use
312      */
313     public WebRequest(final URL url, final HttpMethod submitMethod) {
314         this(url);
315         setHttpMethod(submitMethod);
316     }
317 
318     /**
319      * Returns the target URL.
320      *
321      * @return the target URL
322      */
323     public URL getUrl() {
324         return UrlUtils.toUrlSafe(url_);
325     }
326 
327     /**
328      * Sets the target URL. The URL may be simplified if needed (for instance
329      * eliminating irrelevant path portions like "/./").
330      *
331      * @param url the target URL
332      */
333     public void setUrl(final URL url) {
334         if (url == null) {
335             url_ = null;
336             return;
337         }
338 
339         URL normalizedUrl = url;
340         final String path = normalizedUrl.getPath();
341         if (path.isEmpty()) {
342             if (!normalizedUrl.getFile().isEmpty() || normalizedUrl.getProtocol().startsWith("http")) {
343                 normalizedUrl = buildUrlWithNewPath(normalizedUrl, "/");
344             }
345         }
346         else if (path.contains("/.")) {
347             normalizedUrl = buildUrlWithNewPath(normalizedUrl, StringUtils.removeDots(path));
348         }
349 
350         try {
351             final String idn = IDN.toASCII(normalizedUrl.getHost());
352             if (!idn.equals(normalizedUrl.getHost())) {
353                 normalizedUrl = UrlUtils.getUrlWithNewHost(normalizedUrl, idn);
354             }
355         }
356         catch (final Exception e) {
357             throw new IllegalArgumentException(
358                     "Cannot convert the hostname of URL: '" + normalizedUrl.toExternalForm() + "' to ASCII.", e);
359         }
360 
361         try {
362             url_ = UrlUtils.removeRedundantPort(normalizedUrl).toExternalForm();
363         }
364         catch (final MalformedURLException e) {
365             throw new RuntimeException("Cannot strip default port of URL: " + normalizedUrl.toExternalForm(), e);
366         }
367 
368         // http://john.smith:secret@localhost
369         final String userInfo = normalizedUrl.getUserInfo();
370         if (userInfo != null) {
371             final int splitPos = userInfo.indexOf(':');
372             if (splitPos == -1) {
373                 urlCredentials_ = new HtmlUnitUsernamePasswordCredentials(userInfo, new char[0]);
374             }
375             else {
376                 final String username = userInfo.substring(0, splitPos);
377                 final String password = userInfo.substring(splitPos + 1);
378                 urlCredentials_ = new HtmlUnitUsernamePasswordCredentials(username, password.toCharArray());
379             }
380         }
381     }
382 
383     private static URL buildUrlWithNewPath(final URL url, final String newPath) {
384         try {
385             return UrlUtils.getUrlWithNewPath(url, newPath);
386         }
387         catch (final Exception e) {
388             throw new RuntimeException("Cannot change path of URL: " + url.toExternalForm(), e);
389         }
390     }
391 
392     /**
393      * Returns the proxy host to use.
394      *
395      * @return the proxy host to use
396      */
397     public String getProxyHost() {
398         return proxyHost_;
399     }
400 
401     /**
402      * Sets the proxy host to use.
403      *
404      * @param proxyHost the proxy host to use
405      */
406     public void setProxyHost(final String proxyHost) {
407         proxyHost_ = proxyHost;
408     }
409 
410     /**
411      * Returns the proxy port to use.
412      *
413      * @return the proxy port to use
414      */
415     public int getProxyPort() {
416         return proxyPort_;
417     }
418 
419     /**
420      * Sets the proxy port to use.
421      *
422      * @param proxyPort the proxy port to use
423      */
424     public void setProxyPort(final int proxyPort) {
425         proxyPort_ = proxyPort;
426     }
427 
428     /**
429      * Returns the proxy scheme to use.
430      *
431      * @return the proxy scheme to use
432      */
433     public String getProxyScheme() {
434         return proxyScheme_;
435     }
436 
437     /**
438      * Sets the proxy scheme to use.
439      *
440      * @param proxyScheme the proxy scheme to use
441      *
442      */
443     public void setProxyScheme(final String proxyScheme) {
444         proxyScheme_ = proxyScheme;
445     }
446 
447     /**
448      * Returns whether SOCKS proxy or not.
449      *
450      * Returns whether SOCKS proxy or not.
451      *
452      * @return whether SOCKS proxy or not
453      *
454      */
455     public boolean isSocksProxy() {
456         return isSocksProxy_;
457     }
458 
459     /**
460      * Sets whether SOCKS proxy or not.
461      *
462      * @param isSocksProxy whether SOCKS proxy or not
463      *
464      */
465     public void setSocksProxy(final boolean isSocksProxy) {
466         isSocksProxy_ = isSocksProxy;
467     }
468 
469     /**
470      * Returns the timeout to use.
471      *
472      * @return the timeout to use
473      *
474      */
475     public int getTimeout() {
476         return timeout_;
477     }
478 
479     /**
480      * Sets the timeout to use.
481      *
482      * @param timeout the timeout to use
483      *
484      */
485     public void setTimeout(final int timeout) {
486         timeout_ = timeout;
487     }
488 
489     /**
490      * Returns the form encoding type to use.
491      *
492      * Returns the form encoding type to use.
493      *
494      * @return the form encoding type to use
495      *
496      */
497     public FormEncodingType getEncodingType() {
498         return encodingType_;
499     }
500 
501     /**
502      * Sets the form encoding type to use.
503      *
504      * @param encodingType the form encoding type to use
505      *
506      */
507     public void setEncodingType(final FormEncodingType encodingType) {
508         encodingType_ = encodingType;
509     }
510 
511     /**
512      * Retrieves the request parameters used. Similar to the servlet api function
513      * getParameterMap() this works depending on the request type and collects the
514      * url parameters and the body stuff.<br>
515      * The value is also normalized - null is converted to an empty string.
516      * <p>In contrast to the servlet api this creates a separate KeyValuePair for every
517      * parameter. This means that pairs with the same name can be part of the list. The
518      * servlet api will return a string[] as value for the key in this case.<br>
519      * Additionally this method includes also the uploaded files for multipart post
520      * requests.</p>
521      *
522      * @return the request parameters to use
523      */
524     public List<NameValuePair> getParameters() {
525         // developer note:
526         // this has to be in sync with org.htmlunit.HttpWebConnection.makeHttpMethod(WebRequest, HttpClientBuilder)
527 
528         // developer note:
529         // the spring org.springframework.test.web.servlet.htmlunitHtmlUnitRequestBuilder uses
530         // this method and is sensitive to all the details of the current implementation.
531 
532         final List<NameValuePair> allParameters = new ArrayList<>(
533                 HttpUtils.parseUrlQuery(getUrl().getQuery(), getCharset()));
534 
535         // the servlet api ignores these parameters but to make spring happy we include them
536         final HttpMethod httpMethod = getHttpMethod();
537         if (httpMethod == HttpMethod.POST
538             || httpMethod == HttpMethod.PUT
539             || httpMethod == HttpMethod.PATCH
540             || httpMethod == HttpMethod.DELETE
541             || httpMethod == HttpMethod.OPTIONS) {
542             if (FormEncodingType.URL_ENCODED == getEncodingType()
543                 && httpMethod != HttpMethod.OPTIONS) {
544                 // spring ignores URL_ENCODED parameters for OPTIONS requests
545                 // getRequestParameters and getRequestBody are mutually exclusive
546                 if (getRequestBody() == null) {
547                     allParameters.addAll(getRequestParameters());
548                 }
549                 else {
550                     allParameters.addAll(HttpUtils.parseUrlQuery(getRequestBody(), getCharset()));
551                 }
552             }
553             else if (FormEncodingType.MULTIPART == getEncodingType()) {
554                 if (httpMethod == HttpMethod.POST) {
555                     allParameters.addAll(getRequestParameters());
556                 }
557                 else {
558                     // for PUT, PATCH, DELETE and OPTIONS spring moves the parameters up to the query
559                     // it doesn't replace the query
560                     allParameters.addAll(0, getRequestParameters());
561                 }
562             }
563         }
564 
565         return normalize(allParameters);
566     }
567 
568     private static List<NameValuePair> normalize(final List<NameValuePair> pairs) {
569         if (pairs == null || pairs.isEmpty()) {
570             return pairs;
571         }
572 
573         final List<NameValuePair> resultingPairs = new ArrayList<>();
574         for (final NameValuePair pair : pairs) {
575             resultingPairs.add(pair.normalized());
576         }
577 
578         return resultingPairs;
579     }
580 
581     /**
582      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT
583      * YOUR OWN RISK.</span><br>
584      *
585      * Returns the request parameters to use. If set, these request parameters
586      * will overwrite any request parameters which may be present in the
587      * {@link #getUrl() URL}. Should not be used in combination with the
588      * {@link #setRequestBody(String) request body}.
589      *
590      * @return the request parameters to use
591      */
592     public List<NameValuePair> getRequestParameters() {
593         return requestParameters_;
594     }
595 
596     /**
597      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT
598      * YOUR OWN RISK.</span><br>
599      *
600      * Sets the request parameters to use. If set, these request parameters will
601      * overwrite any request parameters which may be present in the {@link #getUrl()
602      * URL}. Should not be used in combination with the
603      * {@link #setRequestBody(String) request body}.
604      *
605      * @param requestParameters the request parameters to use
606      * @throws RuntimeException if the request body has already been set
607      */
608     public void setRequestParameters(final List<NameValuePair> requestParameters) throws RuntimeException {
609         if (requestBody_ != null) {
610             final String msg = "Trying to set the request parameters, but the request body has already been specified;"
611                     + "the two are mutually exclusive!";
612             throw new RuntimeException(msg);
613         }
614         requestParameters_ = requestParameters;
615     }
616 
617     /**
618      * Returns the body content to be submitted if this is a {@code POST}
619      * request. Ignored for all other request types. Should not be used in
620      * combination with {@link #setRequestParameters(List) request parameters}.
621      *
622      * @return the body content, or {@code null} if not set
623      */
624     public String getRequestBody() {
625         return requestBody_;
626     }
627 
628     /**
629      * Sets the body content to be submitted if this is a {@code POST}, {@code PUT}
630      * or {@code PATCH} request. Other request types result in
631      * {@link IllegalStateException}. Should not be used in combination with
632      * {@link #setRequestParameters(List) request parameters}.
633      *
634      * @param requestBody the body content to be submitted if this is a
635      *                    {@code POST}, {@code PUT} or {@code PATCH} request
636      * @throws IllegalStateException if the request parameters have already been set or
637      *                          this is not a {@code POST}, {@code PUT} or
638      *                          {@code PATCH} request.
639      *
640      */
641     public void setRequestBody(final String requestBody) throws IllegalStateException {
642         if (requestParameters_ != null && !requestParameters_.isEmpty()) {
643             final String msg = "Trying to set the request body, but the request parameters have already been specified;"
644                        + "the two are mutually exclusive!";
645             throw new IllegalStateException(msg);
646         }
647         if (httpMethod_ != HttpMethod.POST
648                 && httpMethod_ != HttpMethod.PUT
649                 && httpMethod_ != HttpMethod.PATCH
650                 && httpMethod_ != HttpMethod.DELETE
651                 && httpMethod_ != HttpMethod.OPTIONS) {
652             final String msg = "The request body may only be set for POST, PUT, PATCH, DELETE or OPTIONS requests!";
653             throw new IllegalStateException(msg);
654         }
655         requestBody_ = requestBody;
656     }
657 
658     /**
659      * Returns the HTTP submit method to use.
660      *
661      * @return the HTTP submit method to use
662      */
663     public HttpMethod getHttpMethod() {
664         return httpMethod_;
665     }
666 
667     /**
668      * Sets the HTTP submit method to use.
669      *
670      * @param submitMethod the HTTP submit method to use
671      */
672     public void setHttpMethod(final HttpMethod submitMethod) {
673         httpMethod_ = submitMethod;
674     }
675 
676     /**
677      * Returns the additional HTTP headers to use.
678      *
679      * @return the additional HTTP headers to use
680      */
681     public Map<String, String> getAdditionalHeaders() {
682         return additionalHeaders_;
683     }
684 
685     /**
686      * Sets the additional HTTP headers to use.
687      *
688      * @param additionalHeaders the additional HTTP headers to use
689      */
690     public void setAdditionalHeaders(final Map<String, String> additionalHeaders) {
691         additionalHeaders_ = additionalHeaders;
692     }
693 
694     /**
695      * Returns whether the specified header name is already included in the
696      * additional HTTP headers. The comparison is case-insensitive.
697      *
698      * @param name the header name to look up
699      * @return {@code true} if the header is present; {@code false} otherwise
700      */
701     public boolean isAdditionalHeader(final String name) {
702         for (final String key : additionalHeaders_.keySet()) {
703             if (name.equalsIgnoreCase(key)) {
704                 return true;
705             }
706         }
707         return false;
708     }
709 
710     /**
711      * Returns the value of the specified additional HTTP header,
712      * or {@code null} if the header is not set. The name comparison
713      * is case-insensitive.
714      *
715      * @param name the header name to look up
716      * @return the header value, or {@code null} if not present
717      */
718     public String getAdditionalHeader(final String name) {
719         final String val = additionalHeaders_.get(name);
720         if (val != null) {
721             return val;
722         }
723 
724         // fall back to case-insensitive scan
725         for (final Map.Entry<String, String> entry : additionalHeaders_.entrySet()) {
726             if (name.equalsIgnoreCase(entry.getKey())) {
727                 return entry.getValue();
728             }
729         }
730         return null;
731     }
732 
733     /**
734      * Sets the {@code Referer} HTTP header to the external form of the given
735      * URL. Does nothing if the URL is {@code null} or does not use the
736      * {@code http} or {@code https} scheme.
737      *
738      * @param url the URL to use as the referer, or {@code null}
739      */
740     public void setRefererHeader(final URL url) {
741         if (url == null || !url.getProtocol().startsWith("http")) {
742             return;
743         }
744 
745         try {
746             // the referrer never contains the credentials and the ref
747             referrer_ = UrlUtils.getUrlWithoutUserInfoAndRef(url).toExternalForm();
748             setAdditionalHeader(HttpHeader.REFERER, referrer_);
749         }
750         catch (final MalformedURLException ignored) {
751             // bad luck use the whole url from the pager
752         }
753     }
754 
755     /**
756      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
757      *
758      * Returns the full referrer (without user info and ref) set by {@link #setRefererHeader(URL)};
759      * the {@code Referer} header is determined from this url and the {@link #getReferrerPolicy() referrer policy}.
760      *
761      * @return the referrer url or {@code null}
762      */
763     public URL getReferrer() {
764         return referrer_ == null ? null : UrlUtils.toUrlSafe(referrer_);
765     }
766 
767     /**
768      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
769      *
770      * Returns the referrer policy used to determine the {@code Referer} header when the request is sent.
771      *
772      * @return the referrer policy or {@code null} if the {@code Referer} header is sent as set
773      */
774     public ReferrerPolicy getReferrerPolicy() {
775         return referrerPolicy_;
776     }
777 
778     /**
779      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
780      *
781      * Sets the referrer policy used to determine the {@code Referer} header when the request is sent
782      * (for the final url, also after redirects).
783      *
784      * @param referrerPolicy the referrer policy or {@code null} if the {@code Referer} header is sent as set
785      */
786     public void setReferrerPolicy(final ReferrerPolicy referrerPolicy) {
787         referrerPolicy_ = referrerPolicy;
788     }
789 
790     /**
791      * Returns the destination of this request, used to compute the
792      * {@code Sec-Fetch-Dest} header (and, unless overridden, the default
793      * {@code Sec-Fetch-Mode}). Defaults to {@link FetchDestination#EMPTY},
794      * which is correct for plain {@code XMLHttpRequest}/{@code fetch()} calls.
795      *
796      * @return the destination of this request
797      */
798     public FetchDestination getFetchDestination() {
799         return fetchDestination_;
800     }
801 
802     /**
803      * Sets the destination of this request.
804      *
805      * @param fetchDestination the destination of this request, or {@code null}
806      *                         to reset to {@link FetchDestination#EMPTY}
807      */
808     public void setFetchDestination(final FetchDestination fetchDestination) {
809         fetchDestination_ = fetchDestination == null ? FetchDestination.EMPTY : fetchDestination;
810     }
811 
812     /**
813      * Returns the cache mode of this request.
814      *
815      * @return the cache mode
816      */
817     public CacheMode getCacheMode() {
818         return cacheMode_;
819     }
820 
821     /**
822      * Sets the cache mode of this request.
823      *
824      * @param cacheMode the cache mode, or {@code null} to reset to {@link CacheMode#DEFAULT}
825      */
826     public void setCacheMode(final CacheMode cacheMode) {
827         cacheMode_ = cacheMode == null ? CacheMode.DEFAULT : cacheMode;
828     }
829 
830     /**
831      * Returns the explicit mode override for this request, if any. When
832      * {@code null} (the default), the mode is derived from the
833      * {@link #getFetchDestination() destination}.
834      *
835      * @return the mode override, or {@code null} if none was set
836      */
837     public FetchMode getFetchModeOverride() {
838         return fetchModeOverride_;
839     }
840 
841     /**
842      * Sets an explicit mode override for this request, e.g. for a {@code fetch()}
843      * call using an explicit {@code mode} option, or a subresource request using
844      * the {@code crossorigin} attribute (which forces CORS mode).
845      *
846      * @param fetchMode the mode to use, or {@code null} to derive it from the
847      *                  {@link #getFetchDestination() destination}
848      */
849     public void setFetchModeOverride(final FetchMode fetchMode) {
850         fetchModeOverride_ = fetchMode;
851     }
852 
853     /**
854      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
855      *
856      * Returns the filter called before a redirect is followed.
857      *
858      * @return the filter or {@code null}
859      * @see #setRedirectFilter(Predicate)
860      */
861     public Predicate<URL> getRedirectFilter() {
862         return redirectFilter_;
863     }
864 
865     /**
866      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
867      *
868      * Sets a filter that is called with the target url before a redirect is followed
869      * (e.g. to check the redirect against the form-action directive of the
870      * Content-Security-Policy). The filter is passed on to the requests of all following
871      * redirects. If the filter returns {@code false}, the redirect is blocked and
872      * {@link WebClient#loadWebResponse(WebRequest)} returns {@code null}.
873      * The filter is not serialized.
874      *
875      * @param redirectFilter the filter or {@code null}
876      */
877     public void setRedirectFilter(final Predicate<URL> redirectFilter) {
878         redirectFilter_ = redirectFilter;
879     }
880 
881     /**
882      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
883      *
884      * Returns the mapper applied to the target url of a redirect.
885      *
886      * @return the mapper or {@code null}
887      * @see #setRedirectUrlMapper(UnaryOperator)
888      */
889     public UnaryOperator<URL> getRedirectUrlMapper() {
890         return redirectUrlMapper_;
891     }
892 
893     /**
894      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
895      *
896      * Sets a mapper that is applied to the target url of a redirect before the redirect filter
897      * is called and the redirect is followed (e.g. to upgrade the url because of the
898      * upgrade-insecure-requests directive of the Content-Security-Policy). The mapper is passed
899      * on to the requests of all following redirects. The mapper is not serialized.
900      *
901      * @param redirectUrlMapper the mapper or {@code null}
902      */
903     public void setRedirectUrlMapper(final UnaryOperator<URL> redirectUrlMapper) {
904         redirectUrlMapper_ = redirectUrlMapper;
905     }
906 
907     /**
908      * Returns whether this request is the result of a navigation backed by
909      * genuine user activation (e.g. a click on a link, a typed URL, or a form
910      * submitted via a click on its submit button) as opposed to one triggered
911      * purely by script (e.g. {@code location.href = ...}, a {@code <meta
912      * http-equiv="refresh">}, or an automatically-loaded {@code <iframe>}).
913      * <p>
914      * Only relevant for requests whose {@code Sec-Fetch-Mode} is {@code
915      * navigate}; used to compute the presence of the {@code Sec-Fetch-User}
916      * header, which real browsers omit entirely (never send as {@code ?0})
917      * whenever this is {@code false}.
918      * </p>
919      *
920      * @return whether this request was triggered by a real user gesture
921      */
922     public boolean isUserActivation() {
923         return userActivation_;
924     }
925 
926     /**
927      * Sets whether this request is the result of a navigation backed by genuine
928      * user activation.
929      *
930      * @param userActivation whether this request was triggered by a real user
931      *                       gesture
932      */
933     public void setUserActivation(final boolean userActivation) {
934         userActivation_ = userActivation;
935     }
936 
937     /**
938      * Returns the URL of the document or script that initiated this request, used
939      * to compute the {@code Sec-Fetch-Site} header. {@code null} means there is
940      * no initiator (e.g. a browser-chrome-initiated navigation such as a typed
941      * URL or bookmark), which maps to {@code Sec-Fetch-Site: none}.
942      * <p>
943      * Note this is tracked separately from the {@code Referer} header: unlike
944      * the referrer, it must not be affected by referrer-policy stripping, since
945      * {@code Sec-Fetch-Site} always reflects the true relationship between the
946      * initiator and the target, even when no {@code Referer} header is sent.
947      * </p>
948      *
949      * @return the URL of the initiator, or {@code null} if there is none
950      */
951     public URL getRequestingUrl() {
952         return requestingUrl_ == null ? null : UrlUtils.toUrlSafe(requestingUrl_);
953     }
954 
955     /**
956      * Sets the URL of the document or script that initiated this request.
957      *
958      * @param requestingUrl the URL of the initiator, or {@code null} if there is
959      *                      none
960      */
961     public void setRequestingUrl(final URL requestingUrl) {
962         requestingUrl_ = requestingUrl == null ? null : requestingUrl.toExternalForm();
963     }
964 
965     /**
966      * Returns the url of the 'site for cookies' of the document that initiated this
967      * (non top-level) request; this is the url of the top-level document if all
968      * ancestors of the document are same-site with it, otherwise 'about:blank'
969      * (no site, never same-site). Used for the SameSite handling of the cookies.
970      *
971      * @return the url of the site for cookies or {@code null} if not set
972      *         (the {@link #getRequestingUrl() requesting url} is used)
973      * @see <a href="https://html.spec.whatwg.org/multipage/browsers.html#site-for-cookies">site for cookies</a>
974      */
975     public URL getSiteForCookies() {
976         return siteForCookies_ == null ? null : UrlUtils.toUrlSafe(siteForCookies_);
977     }
978 
979     /**
980      * Sets the url of the 'site for cookies' of the document that initiated this request.
981      *
982      * @param siteForCookies the url or {@code null}
983      * @see #getSiteForCookies()
984      */
985     public void setSiteForCookies(final URL siteForCookies) {
986         siteForCookies_ = siteForCookies == null ? null : siteForCookies.toExternalForm();
987     }
988 
989     /**
990      * Convenience method for the common case of a top-level navigation (an
991      * anchor/area click, a form submission, a script-driven location change, ...):
992      * sets {@link FetchDestination#DOCUMENT}, the initiator URL, and whether the
993      * navigation was backed by genuine user activation, all in one call.
994      * <p>
995      * Every navigation-triggering call site needs all three of these set
996      * together for correct {@code Sec-Fetch-*} headers; bundling them here
997      * makes it harder for a call site to set some of them and forget the rest.
998      * </p>
999      * <p>
1000      * For navigations whose destination is not {@link FetchDestination#DOCUMENT}
1001      * (e.g. an {@code <iframe>}/{@code <frame>} load), use
1002      * {@link #markAsNavigation(FetchDestination, URL, boolean)} instead.
1003      * </p>
1004      *
1005      * @param requestingUrl the URL of the page initiating this navigation, or
1006      *                      {@code null} if there is none (e.g. a typed URL)
1007      * @param userActivation whether this navigation was triggered by a real
1008      *                       user gesture as opposed to script
1009      */
1010     public void markAsNavigation(final URL requestingUrl, final boolean userActivation) {
1011         markAsNavigation(FetchDestination.DOCUMENT, requestingUrl, userActivation);
1012     }
1013 
1014     /**
1015      * Same as {@link #markAsNavigation(URL, boolean)}, but for navigations whose
1016      * destination isn't a top-level {@link FetchDestination#DOCUMENT} - currently
1017      * only {@code <iframe>}/{@code <frame>} loads ({@link FetchDestination#IFRAME}/
1018      * {@link FetchDestination#FRAME}).
1019      *
1020      * @param destination the navigation's destination
1021      * @param requestingUrl the URL of the page initiating this navigation, or
1022      *                      {@code null} if there is none
1023      * @param userActivation whether this navigation was triggered by a real
1024      *                       user gesture as opposed to script
1025      */
1026     public void markAsNavigation(final FetchDestination destination, final URL requestingUrl,
1027             final boolean userActivation) {
1028         setFetchDestination(destination);
1029         setRequestingUrl(requestingUrl);
1030         setUserActivation(userActivation);
1031     }
1032 
1033     /**
1034      * Sets the specified name/value pair in the additional HTTP headers,
1035      * replacing any existing header with the same name (case-insensitive).
1036      *
1037      * @param name  the header name
1038      * @param value the header value
1039      */
1040     public void setAdditionalHeader(final String name, final String value) {
1041         if (additionalHeaders_.containsKey(name)) {
1042             additionalHeaders_.put(name, value);
1043             return;
1044         }
1045 
1046         // fall back to case-insensitive scan
1047         for (final String key : additionalHeaders_.keySet()) {
1048             if (name.equalsIgnoreCase(key)) {
1049                 additionalHeaders_.put(key, value);
1050                 return;
1051             }
1052         }
1053 
1054         // no existing header found, insert with the given name
1055         additionalHeaders_.put(name, value);
1056     }
1057 
1058     /**
1059      * Removes the specified header from the additional HTTP headers.
1060      * The name comparison is case-insensitive. Does nothing if the
1061      * header is not present.
1062      *
1063      * @param name the header name to remove
1064      */
1065     public void removeAdditionalHeader(final String name) {
1066         if (additionalHeaders_.remove(name) != null) {
1067             return;
1068         }
1069 
1070         // fall back to case-insensitive scan
1071         for (final String key : additionalHeaders_.keySet()) {
1072             if (name.equalsIgnoreCase(key)) {
1073                 additionalHeaders_.remove(key);
1074                 return;
1075             }
1076         }
1077     }
1078 
1079     /**
1080      * Returns the credentials extracted from the URL's userinfo component
1081      * (e.g. {@code http://user:secret@host/}), or {@code null} if none were present.
1082      *
1083      * @return the URL-embedded credentials, or {@code null}
1084      */
1085     public Credentials getUrlCredentials() {
1086         return urlCredentials_;
1087     }
1088 
1089     /**
1090      * Returns the credentials explicitly set via {@link #setCredentials(Credentials)},
1091      * or {@code null} if none were set.
1092      *
1093      * @return the explicitly configured credentials, or {@code null}
1094      */
1095     public Credentials getCredentials() {
1096         return credentials_;
1097     }
1098 
1099     /**
1100      * Sets the credentials to use.
1101      *
1102      * @param credentials the credentials to use
1103      */
1104     public void setCredentials(final Credentials credentials) {
1105         credentials_ = credentials;
1106     }
1107 
1108     /**
1109      * Returns the character set to use to perform the request.
1110      *
1111      * @return the character set to use to perform the request
1112      */
1113     public Charset getCharset() {
1114         return charset_;
1115     }
1116 
1117     /**
1118      * Sets the character set to use to perform the request. The default value is
1119      * {@link java.nio.charset.StandardCharsets#ISO_8859_1}.
1120      *
1121      * @param charset the character set to use to perform the request
1122      */
1123     public void setCharset(final Charset charset) {
1124         charset_ = charset;
1125     }
1126 
1127     /**
1128      * Returns the default character set to use for the response when it does not
1129      * specify one.
1130      *
1131      * @return the default character set to use for the response when it does not
1132      *         specify one.
1133      */
1134     public Charset getDefaultResponseContentCharset() {
1135         return defaultResponseContentCharset_;
1136     }
1137 
1138     /**
1139      * Sets the default character set to use when the response does not declare
1140      * one explicitly.
1141      * <p>
1142      * Unless overridden, the default is
1143      * {@link java.nio.charset.StandardCharsets#ISO_8859_1} (per HTTP/1.1).
1144      * </p>
1145      *
1146      * @param defaultResponseContentCharset the fallback charset; must not be {@code null}
1147      */
1148     public void setDefaultResponseContentCharset(final Charset defaultResponseContentCharset) {
1149         WebAssert.notNull("defaultResponseContentCharset", defaultResponseContentCharset);
1150         defaultResponseContentCharset_ = defaultResponseContentCharset;
1151     }
1152 
1153     /**
1154      * Returns whether the given {@link HttpHint} is currently enabled for this request.
1155      *
1156      * @param hint the hint to check
1157      * @return {@code true} if the hint is enabled; {@code false} otherwise
1158      */
1159     public boolean hasHint(final HttpHint hint) {
1160         if (httpHints_ == null) {
1161             return false;
1162         }
1163         return httpHints_.contains(hint);
1164     }
1165 
1166     /**
1167      * Enables the given {@link HttpHint} for this request.
1168      *
1169      * @param hint the hint to enable
1170      */
1171     public void addHint(final HttpHint hint) {
1172         if (httpHints_ == null) {
1173             httpHints_ = EnumSet.noneOf(HttpHint.class);
1174         }
1175         httpHints_.add(hint);
1176     }
1177 
1178     /**
1179      * {@inheritDoc}
1180      */
1181     @Override
1182     public String toString() {
1183         final StringBuilder builder = new StringBuilder(100)
1184                 .append(getClass().getSimpleName())
1185                 .append("[<url=\"")
1186                 .append(url_)
1187                 .append("\", ").append(httpMethod_)
1188                 .append(", ").append(encodingType_)
1189                 .append(", ").append(requestParameters_)
1190                 .append(", ").append(additionalHeaders_)
1191                 .append(", ").append(credentials_)
1192                 .append(">]");
1193         return builder.toString();
1194     }
1195 
1196     private void writeObject(final ObjectOutputStream oos) throws IOException {
1197         oos.defaultWriteObject();
1198         oos.writeObject(charset_ == null ? null : charset_.name());
1199         oos.writeObject(defaultResponseContentCharset_ == null ? null : defaultResponseContentCharset_.name());
1200     }
1201 
1202     private void readObject(final ObjectInputStream ois) throws ClassNotFoundException, IOException {
1203         ois.defaultReadObject();
1204         final String charsetName = (String) ois.readObject();
1205         if (charsetName != null) {
1206             charset_ = Charset.forName(charsetName);
1207         }
1208         final String defaultResponseContentCharset = (String) ois.readObject();
1209         if (defaultResponseContentCharset != null) {
1210             defaultResponseContentCharset_ = Charset.forName(defaultResponseContentCharset);
1211         }
1212     }
1213 }