gpt4 book ai didi

java - Google Weather API 返回的变音符号显示不正确

转载 作者:行者123 更新时间:2023-11-29 06:05:15 25 4
gpt4 key购买 nike

我正在尝试从 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) {}

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

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

有人对此有想法吗?

谢谢和最好的问候,保罗

最佳答案

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

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

像这样将输入流的编码更改为“Latin1”:

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

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

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

关于java - Google Weather API 返回的变音符号显示不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8757921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com