我正在尝试在我的应用引擎项目中使用 Google Translate v2 api。然而,对于带重音的字符,它的编码是困惑的[例子是单词“student”,在法语中应该是“étudiants”,变成了“Étudiants”]。这是我的代码。
URL url = new URL(
"https://www.googleapis.com/language/translate/v2?key=" + KEY
+ "&q=" + urlEncodedText + "&source=en&target="
+ urlEncodedLang);
try {
InputStream googleStream = url.openStream();
// make a new bufferred reader, by reading the page at the URL given
// above
BufferedReader reader = new BufferedReader(new InputStreamReader(
googleStream));
// temp string that holds text line by line
String line;
// read the contents of the reader/the page by line, until there are
// no lines left
while ((line = reader.readLine()) != null) {
// keep adding each line to totalText
totalText = totalText + line + "\n";
}
// remember to always close the reader
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
在浏览器(Ubuntu 上的 Chrome)中键入相同的 URL 工作正常,并返回包含正确重音字符的 JSON 响应。
我在这里错过了什么? 谢谢
最佳答案
要确保它具有 UTF-8 编码,您必须使用:
BufferedReader reader = new BufferedReader(new InputStreamReader(googleStream, "UTF-8"));
在其他情况下,它使用默认编码,可能是 ISO-8859-1
。
关于java - Google 翻译 v2 api 返回非 UTF-8 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7302798/