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");
转载自:http://www.greenhtml.com/archives/java-call-google-translate-api-for-free.html