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 static java.nio.charset.StandardCharsets.UTF_16BE;
18  import static java.nio.charset.StandardCharsets.UTF_16LE;
19  import static java.nio.charset.StandardCharsets.UTF_8;
20  
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.io.Serializable;
24  import java.net.URL;
25  import java.nio.charset.Charset;
26  import java.util.List;
27  
28  import org.apache.commons.io.ByteOrderMark;
29  import org.apache.commons.io.IOUtils;
30  import org.apache.commons.io.input.BOMInputStream;
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  import org.htmlunit.http.ContentDisposition;
34  import org.htmlunit.http.ContentDispositionParser;
35  import org.htmlunit.http.HttpStatus;
36  import org.htmlunit.util.EncodingSniffer;
37  import org.htmlunit.util.MimeType;
38  import org.htmlunit.util.NameValuePair;
39  import org.htmlunit.util.StringUtils;
40  
41  /**
42   * A response from a web server.
43   *
44   * @author Mike Bowler
45   * @author Brad Clarke
46   * @author Noboru Sinohara
47   * @author Marc Guillemot
48   * @author Ahmed Ashour
49   * @author Ronald Brill
50   * @author Lai Quang Duong
51   */
52  public class WebResponse implements Serializable {
53  
54      private static final Log LOG = LogFactory.getLog(WebResponse.class);
55      private static final ByteOrderMark[] BOM_HEADERS = {
56          ByteOrderMark.UTF_8,
57          ByteOrderMark.UTF_16LE,
58          ByteOrderMark.UTF_16BE};
59  
60      private final long loadTime_;
61      private final WebResponseData responseData_;
62      private final WebRequest request_;
63      private boolean wasContentCharsetTentative_;
64      private boolean wasBlocked_;
65      private String blockReason_;
66      private transient ContentDisposition contentDisposition_;
67      private transient boolean contentDispositionParsed_;
68  
69      /**
70       * Constructs a web response.
71       *
72       * @param responseData      the response data
73       * @param url               Where this response came from
74       * @param requestMethod     the method used to get this response
75       * @param loadTime          How long the response took to be sent
76       */
77      public WebResponse(final WebResponseData responseData, final URL url,
78              final HttpMethod requestMethod, final long loadTime) {
79          this(responseData, new WebRequest(url, requestMethod), loadTime);
80      }
81  
82      /**
83       * Constructs a web response.
84       *
85       * @param responseData      the response data
86       * @param request           the request used to get this response
87       * @param loadTime          How long the response took to be sent
88       */
89      public WebResponse(final WebResponseData responseData,
90              final WebRequest request, final long loadTime) {
91          responseData_ = responseData;
92          request_ = request;
93          loadTime_ = loadTime;
94      }
95  
96      /**
97       * Returns the request used to load this response.
98       *
99       * @return the associated {@link WebRequest}
100      */
101     public WebRequest getWebRequest() {
102         return request_;
103     }
104 
105     /**
106      * Returns the response headers.
107      * @return the response headers as a list of {@link NameValuePair}s
108      */
109     public List<NameValuePair> getResponseHeaders() {
110         return responseData_.getResponseHeaders();
111     }
112 
113     /**
114      * Returns the value of the specified response header.
115      * @param headerName the name of the header whose value is to be returned
116      * @return the header value, {@code null} if no response header exists with this name
117      */
118     public String getResponseHeaderValue(final String headerName) {
119         for (final NameValuePair pair : responseData_.getResponseHeaders()) {
120             if (pair.getName().equalsIgnoreCase(headerName)) {
121                 return pair.getValue();
122             }
123         }
124         return null;
125     }
126 
127     /**
128      * Returns the HTTP status code.
129      * @return the status code that was returned by the server
130      */
131     public int getStatusCode() {
132         return responseData_.getStatusCode();
133     }
134 
135     /**
136      * Returns the HTTP status message.
137      * @return the status message that was returned from the server
138      */
139     public String getStatusMessage() {
140         return responseData_.getStatusMessage();
141     }
142 
143     /**
144      * Returns the response content type.
145      * @return the content type, or an empty string if the {@code Content-Type}
146      *         header is absent
147      */
148     public String getContentType() {
149         final String contentTypeHeader = getResponseHeaderValue(HttpHeader.CONTENT_TYPE_LC);
150         if (contentTypeHeader == null) {
151             // Not technically legal but some servers don't return a content-type
152             return "";
153         }
154         final int index = contentTypeHeader.indexOf(';');
155         if (index == -1) {
156             return contentTypeHeader;
157         }
158         return contentTypeHeader.substring(0, index);
159     }
160 
161     /**
162      * Returns the parsed {@code Content-Disposition} header of this response
163      * (see {@link ContentDispositionParser}). The header is parsed only once.
164      *
165      * @return the parsed header or {@code null} if the response has no {@code Content-Disposition} header
166      */
167     public ContentDisposition getContentDisposition() {
168         if (!contentDispositionParsed_) {
169             contentDisposition_ = ContentDispositionParser.parse(
170                     getResponseHeaderValue(HttpHeader.CONTENT_DISPOSITION));
171             contentDispositionParsed_ = true;
172         }
173         return contentDisposition_;
174     }
175 
176     /**
177      * Returns the content charset specified explicitly in the {@code Content-Type} header
178      * or {@code null} if none was specified.
179      * @return the content charset specified in the header or {@code null} if none was specified
180      */
181     public Charset getHeaderContentCharset() {
182         final String contentType = getResponseHeaderValue(HttpHeader.CONTENT_TYPE_LC);
183         if (contentType == null) {
184             return null;
185         }
186 
187         final int index = contentType.indexOf(';');
188         if (index == -1 || index == 0) {
189             return null;
190         }
191         if (StringUtils.isBlank(contentType.substring(0, index))) {
192             return null;
193         }
194 
195         return EncodingSniffer.extractEncodingFromContentType(contentType);
196     }
197 
198     /**
199      * Returns the content charset for this response, even if no charset was specified explicitly.
200      * <p>
201      * This method always returns a valid charset. This method first checks the {@code Content-Type}
202      * header or the content BOM for a viable charset. If not found, it attempts to determine the
203      * charset based on the type of the content. As a last resort, this method returns the
204      * value of {@link org.htmlunit.WebRequest#getDefaultResponseContentCharset()} which is
205      * {@link java.nio.charset.StandardCharsets#UTF_8} by default.
206      * </p>
207      * @return the content charset for this response
208      */
209     public Charset getContentCharset() {
210         wasContentCharsetTentative_ = false;
211 
212         try (InputStream is = getContentAsStreamWithBomIfApplicable()) {
213             if (is == null) {
214                 return getWebRequest().getDefaultResponseContentCharset();
215             }
216 
217             if (is instanceof BOMInputStream stream) {
218                 final String bomCharsetName = stream.getBOMCharsetName();
219                 if (bomCharsetName != null) {
220                     return Charset.forName(bomCharsetName);
221                 }
222             }
223 
224             Charset charset = getHeaderContentCharset();
225             if (charset != null) {
226                 return charset;
227             }
228 
229             final String contentType = getContentType();
230             switch (DefaultPageCreator.determinePageType(contentType)) {
231                 case HTML -> {
232                     charset = EncodingSniffer.sniffEncodingFromMetaTag(is);
233                     wasContentCharsetTentative_ = true;
234                 }
235                 case XML -> {
236                     charset = EncodingSniffer.sniffEncodingFromXmlDeclaration(is);
237                     if (charset == null) {
238                         charset = UTF_8;
239                     }
240                 }
241                 default -> {
242                     if (MimeType.TEXT_CSS.equals(contentType)) {
243                         charset = EncodingSniffer.sniffEncodingFromCssDeclaration(is);
244                     }
245                 }
246             }
247 
248             if (charset != null) {
249                 return charset;
250             }
251         }
252         catch (final IOException e) {
253             LOG.warn("Error trying to sniff encoding.", e);
254             wasContentCharsetTentative_ = true;
255         }
256         return getWebRequest().getDefaultResponseContentCharset();
257     }
258 
259     /**
260      * Returns whether the charset of the previous call to {@link #getContentCharset()} was "tentative".
261      * <p>
262      * A charset is classed as "tentative" if its detection is prone to false positive/negatives.
263      * </p>
264      * <p>
265      * For example, HTML meta-tag sniffing can be fooled by text that looks-like-a-meta-tag inside
266      * JavaScript code (false positive) or if the meta-tag is after the first 1024 bytes (false negative).
267      * </p>
268      * @return {@code true} if tentative; {@code false} if the charset was determined with confidence
269      *
270      * @see <a href="https://html.spec.whatwg.org/multipage/parsing.html#concept-encoding-confidence">
271      *     https://html.spec.whatwg.org/multipage/parsing.html#concept-encoding-confidence</a>
272      */
273     public boolean wasContentCharsetTentative() {
274         return wasContentCharsetTentative_;
275     }
276 
277     /**
278      * Returns the response content as a string, using the charset/encoding specified in the server response.
279      * @return the response content as a string, using the charset/encoding specified in the server response
280      *         or {@code null} if content retrieval failed
281      */
282     public String getContentAsString() {
283         return getContentAsString(getContentCharset());
284     }
285 
286     /**
287      * Returns the response content as a string, using the specified charset,
288      * rather than the charset/encoding specified in the server response.
289      * If there is a BOM header, the charset parameter will be overwritten by the BOM.
290      * @param encoding the charset/encoding to use to convert the response content into a string
291      * @return the response content as a string or {@code null} if content retrieval failed
292      */
293     public String getContentAsString(final Charset encoding) {
294         if (responseData_ != null) {
295             try (InputStream in = responseData_.getInputStreamWithBomIfApplicable(BOM_HEADERS)) {
296                 if (in instanceof BOMInputStream bomIn) {
297                     // there seems to be a bug in BOMInputStream
298                     // we have to call this before hasBOM(ByteOrderMark)
299                     if (bomIn.hasBOM()) {
300                         if (bomIn.hasBOM(ByteOrderMark.UTF_8)) {
301                             return IOUtils.toString(bomIn, UTF_8);
302                         }
303                         if (bomIn.hasBOM(ByteOrderMark.UTF_16BE)) {
304                             return IOUtils.toString(bomIn, UTF_16BE);
305                         }
306                         if (bomIn.hasBOM(ByteOrderMark.UTF_16LE)) {
307                             return IOUtils.toString(bomIn, UTF_16LE);
308                         }
309                     }
310                     return IOUtils.toString(bomIn, encoding);
311                 }
312 
313                 return IOUtils.toString(in, encoding);
314             }
315             catch (final IOException e) {
316                 LOG.warn(e.getMessage(), e);
317             }
318         }
319         return null;
320     }
321 
322     /**
323      * Returns the length of the content data.
324      * @return the length
325      */
326     public long getContentLength() {
327         if (responseData_ == null) {
328             return 0;
329         }
330         return responseData_.getContentLength();
331     }
332 
333     /**
334      * Returns the response content as an input stream.
335      * @return the response content as an input stream
336      * @throws IOException in case of I/O problems
337      */
338     public InputStream getContentAsStream() throws IOException {
339         return responseData_.getInputStream();
340     }
341 
342     /**
343      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
344      *
345      * Returns the response content as an {@link InputStream}, wrapped in a
346      * {@link BOMInputStream} so that any leading byte-order mark is detected
347      * and skipped automatically.
348      *
349      * @return the input stream, or {@code null} if no response data is available
350      * @throws IOException in case of I/O problems
351      */
352     public InputStream getContentAsStreamWithBomIfApplicable() throws IOException {
353         if (responseData_ != null) {
354             return responseData_.getInputStreamWithBomIfApplicable(BOM_HEADERS);
355         }
356         return null;
357     }
358 
359     /**
360      * Returns the time it took to load this web response, in milliseconds.
361      * @return the time it took to load this web response, in milliseconds
362      */
363     public long getLoadTime() {
364         return loadTime_;
365     }
366 
367     /**
368      * Clean up the response data.
369      */
370     public void cleanUp() {
371         if (responseData_ != null) {
372             responseData_.cleanUp();
373         }
374     }
375 
376     /**
377      * Returns whether the response has a successful HTTP status code.
378      *
379      * @return {@code true} if the status code is in the 2xx range
380      */
381     public boolean isSuccess() {
382         final int statusCode = getStatusCode();
383         return statusCode >= HttpStatus.OK_200 && statusCode < HttpStatus.MULTIPLE_CHOICES_300;
384     }
385 
386     /**
387      * Returns whether the response has a successful HTTP status code or a use-proxy redirection.
388      *
389      * @return {@code true} if the status code is in the 2xx range or 305
390      */
391     public boolean isSuccessOrUseProxy() {
392         final int statusCode = getStatusCode();
393         return (statusCode >= HttpStatus.OK_200 && statusCode < HttpStatus.MULTIPLE_CHOICES_300)
394                 || statusCode == HttpStatus.USE_PROXY_305;
395     }
396 
397     /**
398      * Returns whether the response has a successful HTTP status code, a proxy redirection, or a not-modified status.
399      *
400      * @return {@code true} if the status code is in the 2xx range, 304 (Not Modified), or 305 (Use Proxy)
401      */
402     public boolean isSuccessOrUseProxyOrNotModified() {
403         return isSuccessOrUseProxy() || getStatusCode() == HttpStatus.NOT_MODIFIED_304;
404     }
405 
406     /**
407      * Returns whether the request was blocked.
408      *
409      * @return {@code true} if the request was blocked
410      */
411     public boolean wasBlocked() {
412         return wasBlocked_;
413     }
414 
415     /**
416      * Returns the reason for blocking or null.
417      *
418      * @return the reason for blocking, or {@code null} if the request was not blocked
419      */
420     public String getBlockReason() {
421         return blockReason_;
422     }
423 
424     /**
425      * Sets the wasBlocked state to true.
426      *
427      * @param blockReason the reason
428      */
429     public void markAsBlocked(final String blockReason) {
430         wasBlocked_ = true;
431         blockReason_ = blockReason;
432     }
433 }