[英]Umlauts returned by Google Weather API not displayed properly
我正在嘗試從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已經包含損壞的變音符號。
有沒有人對此有所了解?
謝謝你,問候保羅
歡迎來到Character Encodings的神奇世界。 請把你的理智放在門邊的架子上......
您很可能需要使用source.setEncoding(encoding)
並為網頁指定正確的字符編碼 - 如果您很幸運,編碼可能實際上在標題中指定。
將輸入流的編碼更改為“Latin1”,如下所示:
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, Charset.forName("Latin1")));
在我的機器上測試時返回正確的德語字符:
<current_conditions><condition data="Meistens bewölkt"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.