【问题标题】:Java InputStreamReader from URL does not encode "Umlaute"来自 URL 的 Java InputStreamReader 不编码“Umlaute”
【发布时间】:2017-08-02 10:14:50
【问题描述】:

我尝试从 URL 读取 html 内容。当我不想将内容打印到控制台时,像ä、ö、ü 这样的“元音变音”显示错误。

URL url = new URL("http://www.lauftreff.de/laeufe/halbmarathon-1-2017.html");
URLConnection conn = url.openConnection();
InputStreamReader input = new InputStreamReader(conn.getInputStream(),StandardCharsets.ISO_8859_1);
BufferedReader bi = new BufferedReader(input);
String inputLine;
while((inputLine = bi.readLine()) != null){
    System.out.println(inputLine);
}

在 html 的标题中,字符集的信息显示为 ISO_8859_1。 UTF-8 也不起作用。 有没有人有想法怎么办?

【问题讨论】:

  • 您的控制台不支持 UTF-8 或 ISO_8859_1?
  • 您得到了正确的结果。但是,“ä”表示为ä

标签: java html url inputstreamreader


【解决方案1】:

在网站中,元音变音被解码为 HTML 实体。所以你需要解码这些。下面的代码应该可以工作,但它未经测试。

URL url = new URL("http://www.lauftreff.de/laeufe/halbmarathon-1-2017.html");
URLConnection conn = url.openConnection();
InputStreamReader input = new InputStreamReader(conn.getInputStream(),StandardCharsets.ISO_8859_1);
BufferedReader bi = new BufferedReader(input);
String inputLine;
while((inputLine = bi.readLine()) != null){
    inputLine = StringEscapeUtils.unescapeHtml4(inputLine);
    System.out.println(inputLine);
}

【讨论】:

  • 是的,这正是我也注意到的。
  • 你应该提到StringEscapeUtils的来源:它不是JDK的一部分。
  • 谢谢!将 lang3 添加到 maven 依赖项!
猜你喜欢
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
  • 2014-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-25
相关资源
最近更新 更多