View Javadoc
1   /*
2    * Copyright (c) 2002-2025 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_8;
18  
19  import java.nio.charset.Charset;
20  import java.nio.charset.StandardCharsets;
21  import java.util.HashMap;
22  import java.util.Map;
23  
24  import org.htmlunit.html.HtmlPage;
25  import org.htmlunit.util.MimeType;
26  import org.htmlunit.util.mocks.WebResponseMock;
27  import org.junit.jupiter.api.Test;
28  
29  /**
30   * Tests for {@link WebResponse}.
31   *
32   * @author Marc Guillemot
33   * @author Ahmed Ashour
34   */
35  public class WebResponse2Test extends SimpleWebTestCase {
36  
37      /**
38       * @throws Exception if the test fails
39       */
40      @Test
41      public void charsetInMetaTag() throws Exception {
42          final String html = DOCTYPE_HTML
43              + "<html>\n"
44              + "<head><meta content='text/html; charset=utf-8' http-equiv='Content-Type'/></head>\n"
45              + "<body>foo</body>\n"
46              + "</html>";
47          final HtmlPage page = loadPage(html);
48          assertSame(UTF_8, page.getWebResponse().getContentCharset());
49          assertEquals(html, page.getWebResponse().getContentAsString());
50      }
51  
52      /**
53       * @throws Exception if the test fails
54       */
55      @Test
56      public void getHeaderContentCharset() {
57          testHeaderContentCharset(StandardCharsets.UTF_8, MimeType.TEXT_HTML + ";charset=utf-8");
58  
59          testHeaderContentCharset(null, "  \t ;charset=utf-8");
60          testHeaderContentCharset(null, ";charset=utf-8");
61          testHeaderContentCharset(null, "charset=utf-8");
62      }
63  
64      private static void testHeaderContentCharset(final Charset expected, final String contentTypeHeader) {
65          final Map<String, String> headers = new HashMap<>();
66          headers.put(HttpHeader.CONTENT_TYPE, contentTypeHeader);
67  
68          final WebResponseMock response = new WebResponseMock(null, headers);
69          assertEquals(expected, response.getHeaderContentCharset());
70      }
71  }