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