2

您好我想使用 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);
            }
4

4 回答 4

6

您需要为 InputStreamReader 指定字符集,例如

InputStreamReader(url.openStream(), "UTF-8") 
于 2011-05-31T14:16:42.637 回答
2

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

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

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

我可以想象您必须考虑许多不同的附加问题才能正确解析网页。但是有不同的可用于 Java 的 HTTP 客户端库,例如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>
于 2011-05-31T14:22:31.623 回答
0

尝试设置一个字符集。

new BufferedReader(new InputStreamReader(url.openStream(), Charset.forName("UTF-8") ));
于 2011-05-31T14:17:03.277 回答
0

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

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

于 2011-05-31T14:17:42.153 回答