免费翻译接口API
方式一
接口地址: https://api.kertennet.com/live/translate
返回格式: json
请求方式: GET
请求示例: https://api.kertennet.com/live/translate?text=翻译接口&to=en
该API是私人维护
封装工具类
private static String getTranslator(String word) {
try {
String uri = "https://api.kertennet.com/live/translate?text=" + word + "&to=en";
HttpClient httpClient = new DefaultHttpClient();
HttpGet method = new HttpGet(uri);
HttpResponse response = httpClient.execute(method);
String body = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
Translate parse = JsonUtil.parse(body, Translate.class);
if (Func.isNotEmpty(parse)) {
return parse.getData().getTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
return word;
}
封装返回对象
@Data
public class Translate {
private String code;
private String message;
private Data data;
@lombok.Data
public class Data {
private String source;
private String target;
}
}
方式二
有道翻译
/**
* 有道翻译
*
* @param word
* @return
*/
private static String getTranslator(String word) {
try {
String uri = "https://fanyi.youdao.com/translate?&doctype=json&type=AUTO&i=" + word;
HttpClient httpClient = new DefaultHttpClient();
HttpGet method = new HttpGet(uri);
HttpResponse response = httpClient.execute(method);
String body = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
return getJsonValue(body);
} catch (IOException e) {
e.printStackTrace();
}
return word;
}
public static String getJsonValue(String jsonStr) {
// 将字符串解析成Json对象
JSONObject jsonObj = JSON.parseObject(jsonStr);
// 获取translateResult数组
JSONArray translateResult = jsonObj.getJSONArray("translateResult");
// 获取第一个数组元素
JSONArray arr = translateResult.getJSONArray(0);
// 获取第一个元素对象
JSONObject obj = arr.getJSONObject(0);
// 获取tgt的值
String tgt = obj.getString("tgt");
return tgt;
}