这篇文章上次修改于 2233 天前,可能其部分内容已经发生变化,如有疑问可询问作者。
谷歌的翻译api是收费的,但是为了临时用一下,可以免费hack他们网页版的翻译接口,而且不需要验证。
[1]java代码如下
public class Translator {
public String translate(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);
HttpURLConnection con = (HttpURLConnection) 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 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);
String result ="";
for(var i =0;i < jsonArray2.length();i ++){
result += ((JSONArray) jsonArray2.get(i)).get(0).toString();
}
return result;
}
}
[2]调用translate(“en”,”zh-CN”,”hello world”);即可
没有评论