我正在尝试使用 translate.googleapis.com
将英语翻译成阿拉伯语。
它适用于除一个字母之外的所有字母,它总是将字母“ف”显示为“�?” 有什么建议吗?
private static String callUrlAndParseResult(String langFrom, String langTo, String word) throws Exception {
String url =
"https://translate.googleapis.com/translate_a/single?" + "client=gtx&" + "sl=" + langFrom + "&tl=" +
langTo + "&dt=t&q=" + URLEncoder.encode(word, "UTF-8");
URL obj = new URL(url);
URLConnection con = obj.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return parseResult(response.toString());
}
private static String parseResult(String inputJson) throws Exception {
/*
* inputJson for word 'hello' translated to language Hindi from English-
* [[["??????","hello",,,1]],,"en"]
* We have to get '?????? ' from this json.
*/
JSONArray jsonArray = new JSONArray(inputJson);
JSONArray jsonArray2 = (JSONArray) jsonArray.get(0);
JSONArray jsonArray3 = (JSONArray) jsonArray2.get(0);
return jsonArray3.get(0).toString();
}
public static void main(String[] args) {
try {
String word = callUrlAndParseResult("en", "ar", "phone");
System.out.println(new String(word.getBytes(), Charset.forName("UTF-8")));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
我正在使用 jdeveloper 12cR2
最佳答案
请注意,每当您使用Reader
时,字符集之间都会进行转换。如果您不指定字符集,它将使用系统默认的字符集对传入的字节流进行编码,如果传入的字节流实际上与您的系统的字符集不同,您就会遇到麻烦。
因此,建议在使用Reader
时指定特定的字符集。
所以你的代码应该如下所示。
private static String callUrlAndParseResult(String langFrom, String langTo, String word) throws Exception {
String url =
"https://translate.googleapis.com/translate_a/single?" + "client=gtx&" + "sl=" + langFrom + "&tl=" +
langTo + "&dt=t&q=" + URLEncoder.encode(word, "UTF-8");
URL obj = new URL(url);
URLConnection con = obj.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return parseResult(response.toString());
}
private static String parseResult(String inputJson) throws Exception {
/*
* inputJson for word 'hello' translated to language Hindi from English-
* [[["??????","hello",,,1]],,"en"]
* We have to get '?????? ' from this json.
*/
JSONArray jsonArray = new JSONArray(inputJson);
JSONArray jsonArray2 = (JSONArray) jsonArray.get(0);
JSONArray jsonArray3 = (JSONArray) jsonArray2.get(0);
return jsonArray3.get(0).toString();
}
public static void main(String[] args) {
try {
String word = callUrlAndParseResult("en", "ar", "phone");
System.out.println(word);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
关于java - Java 中翻译 API 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46540988/