1

GoogleWeatherAPIから天気情報を読み込もうとしています。

私のコードは次のようになります。

            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には破損したウムラウトが含まれています。

誰かがそれについて考えを持っていますか?

よろしくお願いします、ポール

4

1 に答える 1

3

文字エンコーディングの魔法の世界へようこそ。ドアのそばのラックに正気を残してください...

ほとんどsource.setEncoding(encoding)の場合、Web ページの正しい文字エンコーディングを使用および指定する必要があります。運が良ければ、エンコーディングが実際にヘッダーで指定されている可能性があります。

次のように、入力ストリームのエンコーディングを「Latin1」に変更します。

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

私のマシンでテストすると、これは適切なドイツ語の文字を返します。

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

于 2012-01-06T12:48:08.343 に答える