2011-09-04 85 views
1

我想在我的應用程序引擎項目中使用谷歌翻譯V2 API。然而,對於重音字符,它的編碼是混亂的[例如單詞「學生」,這應該是法語「étudiants」,變成「étudiants」]。這是我的代碼。谷歌翻譯V2 API返回非UTF-8字符

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(); 
    } 

在瀏覽器(Chrome在Ubuntu)輸入相同的URL工作正常,並返回包含正確的重音符號JSON響應。

我在這裏錯過了什麼? 感謝

回答

1

爲了確保它有UTF-8編碼,您必須使用:

BufferedReader reader = new BufferedReader(new InputStreamReader(googleStream, "UTF-8")); 
在其他情況下

它使用的默認編碼,也許這是一個ISO-8859-1

+1

感謝這個快速簡單的解決方案。 – Animesh