赞
踩
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; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。