【问题标题】:Reading the content of web page阅读网页内容
【发布时间】:2011-05-31 14:13:35
【问题描述】:

嗨 我想使用 java 阅读包含德语字符的网页内容,不幸的是,德语字符显示为奇怪的字符。 请提供任何帮助 这是我的代码:

String link = "some german link";

            URL url = new URL(link);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }

【问题讨论】:

  • 这听起来像是由于您可以提供给 InputStreamReader() 的字符集。什么字符不能显示?
  • 为什么不改用jsoup呢?

标签: java character-encoding inputstreamreader


【解决方案1】:

你需要为你的 InputStreamReader 指定字符集,比如

InputStreamReader(url.openStream(), "UTF-8") 

【讨论】:

  • 这可能会奏效,但您必须考虑并非所有 Web 服务器都以 UTF8 格式提供其内容。您必须处理多个标头信息(HTTP:Content-Type、HTML:Content-Type、编码或字符集)
【解决方案2】:

您必须设置正确的编码。您可以在 HTTP 标头中找到编码:

Content-Type: text/html; charset=ISO-8859-1

这可能会在 (X)HTML 文档中被覆盖,请参阅HTML Character encodings

我可以想象,您必须考虑许多不同的附加问题才能正确解析网页。但是有不同的 HTTP 客户端库可用于 Java,例如org.apache.httpcomponents。代码将如下所示:

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.spiegel.de");

try
{
  HttpResponse response = httpclient.execute(httpGet);
  HttpEntity entity = response.getEntity();
  if (entity != null)
  {
    System.out.println(EntityUtils.toString(entity));
  }
}
catch (ClientProtocolException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}

这是maven神器:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.1.1</version>
  <type>jar</type>
  <scope>compile</scope>
</dependency>

【讨论】:

  • 我刚刚将阅读器的编码更改为 ISO-8859-1,一切都进行得很完美。谢谢 :)
【解决方案3】:

尝试设置一个字符集。

new BufferedReader(new InputStreamReader(url.openStream(), Charset.forName("UTF-8") ));

【讨论】:

    【解决方案4】:

    首先,确认您使用的字体可以支持您尝试显示的特定德语字符。很多字体并不包含所有字符,当它是一个简单的“缺少字符”问题时,寻找其他原因是一件很痛苦的事情。

    如果这不是问题,那么您输入或输出的字符集有误。字符集决定了代表字符的数字如何映射到字形(或代表字符的图片)。 Java 通常在内部使用 UTF-8;所以输出流可能不是问题。检查输入流。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 2018-06-18
      • 2016-07-06
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多