【问题标题】:Umlauts returned by Google Weather API not displayed properlyGoogle Weather API 返回的变音符号未正确显示
【发布时间】:2012-02-04 04:30:05
【问题描述】:

我正在尝试从 Google Weather API 读取天气信息。

我的代码如下所示:

            String googleWeatherUrl = "http://www.google.de/ig/api?weather=berlin&hl=de";
    InputStream in = null;
    String xmlString = "";
    String line = "";
    URL url = null;
    try {
        url = new URL(googleWeatherUrl);
        in = url.openStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, UTF_8));
        while ((line = bufferedReader.readLine()) != null) {
            xmlString += line;
        }
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    } 

    DocumentBuilder builder = null;
    Document doc = null;
    try {
        builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource source = new InputSource(new StringReader(xmlString));
        doc = builder.parse(source);

    } catch (ParserConfigurationException e) {} 
              catch (FactoryConfigurationError e) {} 
              catch (SAXException e) {} catch (IOException e) {}

基本上它就像一个魅力,但是当返回的数据包含变音符号(ö,ü,ä,...)时,这些字符将无法正确显示。在 Eclipse 以及浏览器或相应的源代码中,它们显示为矩形(或类似奇怪的东西)。

实际上变量 xmlString 已经包含损坏的变音符号。

有人对此有想法吗?

感谢和最好的问候, 保罗

【问题讨论】:

  • 你应该告诉我们这些字符在哪里丢失了。 xmlString 是否仍然包含它们?
  • 好电话。我已经编辑了这个问题。 xmlString 已损坏...
  • 服务器的响应是 ISO-8859-1(干得好,谷歌),而不是 UTF-8。这就是为什么它是错误的。我认为您不需要手动设置编码,开箱即用可能就可以了。如果不是,您别无选择,只能使用HttpURLConnection 获取 Content-Type 标头,解析编码然后进行相应设置。我只是希望 Sun 的人真正考虑一下。

标签: java api internationalization weather


【解决方案1】:

欢迎来到字符编码的神奇世界。请把你的理智留在门边的架子上......

您很可能需要使用 source.setEncoding(encoding) 并为网页指定正确的字符编码 - 如果幸运的话,编码实际上可能在标题中指定。

将输入流的编码更改为“Latin1”,如下所示:

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, Charset.forName("Latin1")));

在我的机器上测试时,这会返回正确的德语字符:

<current_conditions><condition data="Meistens bewölkt"/>

【讨论】:

    猜你喜欢
    • 2018-10-15
    • 1970-01-01
    • 2015-05-24
    • 2014-01-04
    • 2022-11-02
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多