1
我正在嘗試從Google Weather API讀取天氣信息。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) {}
基本上它像一個風情萬種,但是當返回的數據中包含變音符號(O,U,A,...),那麼這些字符顯示不正確。在Eclipse以及瀏覽器或相應的源代碼中,它們顯示爲矩形(或類似的奇怪)。
實際上已經是變量xmlString包含損壞的元音變音。
有沒有人有這個想法?
感謝和問候, 保羅
你應該告訴我們這些字符:在我的機器上測試
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, Charset.forName("Latin1")));
這將返回正確的德語字符:
更改您的InputStream的編碼爲 「Latin1的」 像這樣迷路了。 'xmlString'是否仍然包含它們? – home 2012-01-06 12:46:19
好電話。我編輯了這個問題。 xmlString已損壞... – Paul 2012-01-06 13:00:26
服務器的響應是ISO-8859-1(偉大的工作,谷歌),而不是UTF-8。這就是爲什麼它是錯的。我認爲你不需要手動設置編碼,它可能是開箱即用的。如果不是,您別無選擇,只能使用[HttpURLConnection](http://docs.oracle.com/javase/1.4.2/docs/api/java/net/HttpURLConnection.html)獲取Content-Type標頭,解析編碼,然後相應地設置它。我只是希望來自Sun的人真的想到了它。 – 2012-01-06 18:37:47