【问题标题】:Google translate v2 api returning non UTF-8 characters谷歌翻译 v2 api 返回非 UTF-8 字符
【发布时间】:2011-09-04 23:40:22
【问题描述】:

我正在尝试在我的应用引擎项目中使用 Google Translate v2 api。然而,对于重音字符,它的编码是混乱的[例如“学生”这个词,在法语中应该是“é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 响应。

我在这里缺少什么? 谢谢

【问题讨论】:

    标签: java google-app-engine encoding google-translate


    【解决方案1】:

    要确保它具有 UTF-8 编码,您必须使用:

    BufferedReader reader = new BufferedReader(new InputStreamReader(googleStream, "UTF-8"));
    

    在其他情况下,它使用默认编码,可能是ISO-8859-1

    【讨论】:

    • 感谢这个快速简单的解决方案。
    【解决方案2】:

    您也可以尝试使用 Google Translate API v2 for Java 为您完成此操作。

    【讨论】:

      猜你喜欢
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      • 2018-12-25
      • 2015-04-04
      • 2012-01-26
      • 1970-01-01
      • 2012-05-14
      相关资源
      最近更新 更多