谷歌云翻译和Java的错误编码

Dee*_*ems 6 java encoding google-translate google-cloud-platform

我正在尝试使用谷歌云翻译。我认为问题在于谷歌云翻译使用 UTF8,而 jvm 使用 UTF16。所以我在翻译中遇到了一些错字。例如 :

      public static void main(String... args) throws Exception {
    // Instantiates a client
    Translate translate = TranslateOptions.getDefaultInstance().getService();

    // The text to translate
    String text = "Bonjour, à qui dois-je répondre? Non, C'est l'inverse...";

    // Translates some text into Russian
    Translation translation =
        translate.translate(
            text,
            TranslateOption.sourceLanguage("fr"),
            TranslateOption.targetLanguage("en"));


    System.out.printf("Text: %s%n", text);
    System.out.printf("Translation: %s%n", StringEscapeUtils.unescapeHtml(translation.getTranslatedText()));
  }
Run Code Online (Sandbox Code Playgroud)

将返回 :

“翻译:你好,我该回答谁?不,相反……”

代替 :

翻译:你好,我应该回答谁?不,恰恰相反……

我们无法更改 java 字符串的编码,并且 Google Cloud Api 不会接受任何内容(字节 []?),但字符串。

有人知道如何解决吗?

感谢您阅读

编辑:此代码现在正在运行,我添加了来自 commons.apache 依赖项的 StringEscapeUtils.unescapeHtml。我不知道是否有其他方法可以做到。

MrS*_*h42 2

不是UTF8/UTF16的问题。
google的答案是html编码的。

https://en.wikipedia.org/wiki/Unicode_and_HTML

如果您想在 xml/html 上下文中仅使用 ASCII 传输 unicode 字符,则这种情况很常见。