百度,有道,谷歌翻译API
API翻译
百度,有道,谷歌API翻译(只针对中英相互翻译),其他语言翻译需要对应from,to的code
百度翻译
package fills.tools.translate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSON; public class BaiduTranslateTools { public static void main(String[] args) throws Exception{ String en = doBdTranslate("测试一下", "zh", "en"); String zh = doBdTranslate("test", "en", "zh"); System.out.println(en); System.out.println(zh); } private static CloseableHttpClient httpClient = HttpClients.createDefault(); /** * 封装百度翻译请求参数 * @param query * @param from zh * @param to en * @return String * @throws Exception */ public static String doBdTranslate(String query,String from,String to)throws Exception{ String url = "https://fanyi.baidu.com/v2transapi"; Map<String,String> params = new HashMap<String,String>(); params.put("from",from); params.put("to",to); params.put("transtype","translang"); params.put("simple_means_flag","3"); params.put("sign",runByJs(query,"sig",getBdJs())); params.put("token","75f7eb4170c6dba7a1d84c76611205c3"); params.put("domain","common"); params.put("query",query); return bdGetResult(bdTranslate(url, params)); } /** * 封装百度翻译接口 模拟浏览器请求 * @param url * @param map * @return String * @throws Exception */ private static String bdTranslate(String url,Map<String,String> map) throws Exception{ try { HttpPost request = new HttpPost(url); request.setEntity(new UrlEncodedFormEntity(map2list(map), "UTF-8")); request.setHeader("Cookie","BIDUPSID=518EFD25B0E401331F59B9BDC8388898; BAIDUID=DA7060B673236FB3427E0D66755262B9:FG=1; PSTM=1636594736; __yjs_duid=1_57b3cd04392832a6fbd32d39e48784831636600728790; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; BDUSS=phdjFZaTJRZ3lPeW1OaHg0WXFyMFgtNWZ6QXNkczh3cEd-Sn5INjg3dG9nc0poRVFBQUFBJCQAAAAAAAAAAAEAAACHLc4ceXNmd3p6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGj1mmFo9ZpheW; H_PS_PSSID=34446_35104_31254_35049_34584_34518_35245_34578_26350_35146; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1637568947; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1637569056; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; delPer=0; PSINO=2; BDRCVFR[Fc9oatPmwxn]=mk3SLVN4HKm; BA_HECTOR=8hag058g0gag8g218f1gpp7gb0r"); request.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0"); request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); request.setHeader("Host","fanyi.baidu.com"); request.setHeader("Origin","https://fanyi.baidu.com"); request.setHeader("Referer","https://fanyi.baidu.com/?aldtype=16047"); request.setHeader("X-Requested-With","XMLHttpRequest"); CloseableHttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); response.getEntity().getContent().close(); response.close(); return result; } catch (Exception e) { throw e; } } /** * 处理百度翻译结果 * @param json * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static String bdGetResult(String json){ Map<String ,Object> result = JSON.parseObject(json, Map.class); Map res = (Map)result.get("trans_result"); List<Map> r = (List<Map>)res.get("data"); if(!r.isEmpty()){ return (r.get(0).get("dst")+"").replace(",", ""); } return null; } /** * * @param param 一个入参 * @param method 方法 * @param jsCode js 代码 * @return String */ public static String runByJs(String param,String method,String jsCode){ String res = null; try { ScriptEngine bdToken = new ScriptEngineManager().getEngineByName("js"); bdToken.eval(jsCode); Invocable inv2 = (Invocable) bdToken; res =(String)inv2.invokeFunction(method,param); } catch (Exception e) { res = null; } return res; } /** * 百度js 签名算法 * @return String */ private static String getBdJs(){ StringBuffer bd = new StringBuffer(); bd.append("var i = '320305.131321201'; "); bd.append("function n(r, o) { "); bd.append(" for (var t = 0; t < o.length - 2; t += 3) { "); bd.append(" var a = o.charAt(t + 2); "); bd.append(" a = a >= 'a' ? a.charCodeAt(0) - 87 : Number(a), "); bd.append(" a = '+' === o.charAt(t + 1) ? r >>> a: r << a, "); bd.append(" r = '+' === o.charAt(t) ? r + a & 4294967295 : r ^ a "); bd.append(" } "); bd.append(" return r "); bd.append("} "); bd.append("var sig = function e(r) { "); bd.append(" var o = r.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g); "); bd.append(" if (null === o) { "); bd.append(" var t = r.length; "); bd.append(" t > 30 && (r = '' + r.substr(0, 10) + r.substr(Math.floor(t / 2) - 5, 10) + r.substr( - 10, 10)) "); bd.append(" } else { "); bd.append(" for (var e = r.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/), C = 0, h = e.length, f = []; h > C; C++)'' !== e[C] && f.push.apply(f, a(e[C].split(''))), "); bd.append(" C !== h - 1 && f.push(o[C]); "); bd.append(" var g = f.length; "); bd.append(" g > 30 && (r = f.slice(0, 10).join('') + f.slice(Math.floor(g / 2) - 5, Math.floor(g / 2) + 5).join('') + f.slice( - 10).join('')) "); bd.append(" } "); bd.append(" var u = void 0, "); bd.append(" l = '' + String.fromCharCode(103) + String.fromCharCode(116) + String.fromCharCode(107); "); bd.append(" u = null !== i ? i: (i = window[l] || '') || ''; "); bd.append(" for (var d = u.split('.'), m = Number(d[0]) || 0, s = Number(d[1]) || 0, S = [], c = 0, v = 0; v < r.length; v++) { "); bd.append(" var A = r.charCodeAt(v); "); bd.append(" 128 > A ? S[c++] = A: (2048 > A ? S[c++] = A >> 6 | 192 : (55296 === (64512 & A) && v + 1 < r.length && 56320 === (64512 & r.charCodeAt(v + 1)) ? (A = 65536 + ((1023 & A) << 10) + (1023 & r.charCodeAt(++v)), S[c++] = A >> 18 | 240, S[c++] = A >> 12 & 63 | 128) : S[c++] = A >> 12 | 224, S[c++] = A >> 6 & 63 | 128), S[c++] = 63 & A | 128) "); bd.append(" } "); bd.append(" for (var p = m, "); bd.append(" F = '' + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(97) + ('' + String.fromCharCode(94) + String.fromCharCode(43) + String.fromCharCode(54)), D = '' + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(51) + ('' + String.fromCharCode(94) + String.fromCharCode(43) + String.fromCharCode(98)) + ('' + String.fromCharCode(43) + String.fromCharCode(45) + String.fromCharCode(102)), b = 0; b < S.length; b++) p += S[b], "); bd.append(" p = n(p, F); "); bd.append(" return p = n(p, D), "); bd.append(" p ^= s, "); bd.append(" 0 > p && (p = (2147483647 & p) + 2147483648), "); bd.append(" p %= 1e6, "); bd.append(" p.toString() + '.' + (p ^ m) "); bd.append("} "); return bd.toString(); } /** * 转换请求参数 * @param paramsMap * @return */ private static List<? extends NameValuePair> map2list(Map<String, String> paramsMap) { List<NameValuePair> listParams = new ArrayList<NameValuePair>(); Set<String> keys = paramsMap.keySet(); for (String key : keys) { listParams.add(new BasicNameValuePair(key, paramsMap.get(key))); } return listParams; } } |
运行结果
有道翻译
package fills.tools.translate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSON; import fills.tools.md5.MD5Util; import fills.tools.util.EncodingCheck; public class YoudaoTranslateTools { public static void main(String[] args) throws Exception{ String en = doYdTranslate("测试一下", "zh", "en"); String zh = doYdTranslate("test", "en", "zh"); System.out.println(en); System.out.println(zh); } private static CloseableHttpClient httpClient = HttpClients.createDefault(); /** * 封装有道翻译请求参数 * @param query * @param from zh * @param to en * @return String * @throws Exception */ public static String doYdTranslate(String query,String from,String to) throws Exception{ String newQuery = EncodingCheck.gbkToUtf8(query); String url = "https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"; Long time = System.currentTimeMillis(); String slat = time+""+ (long) (Math.random() * 10 + 1); //签名算法 String sign = MD5Util.md5("fanyideskweb" + newQuery + slat + "Y2FYu%TNSbMCxc3t2u^XT"); Map<String,String> params = new HashMap<String,String>(); params = new HashMap<String,String>(); params.put("i", newQuery); //params.put("from", "AUTO"); //params.put("to", "AUTO"); params.put("from", from); params.put("to", to); params.put("smartresult", "dict"); params.put("client", "fanyideskweb"); params.put("salt", slat); params.put("sign", sign); params.put("doctype", "json"); params.put("bv","e2a78ed30c66e16a857c5b6486a1d326"); params.put("lts",""+time); params.put("version", "2.1"); params.put("keyfrom", "fanyi.web"); params.put("action", "FY_BY_CLICKBUTTION"); return ydGetResult(YoudaoTranslateTools.ydTranslate(url, params)); } /** * 封装有道翻译接口 * @param url * @param map * @return * @throws Exception */ private static String ydTranslate(String url,Map<String,String> map) throws Exception{ try { HttpPost request = new HttpPost(url); request.setEntity(new UrlEncodedFormEntity(map2list(map), "UTF-8")); request.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); request.setHeader("Cookie","OUTFOX_SEARCH_USER_ID_NCOO=2112457812.6057248; OUTFOX_SEARCH_USER_ID=\"1568208620@10.105.137.204\"; YOUDAO_MOBILE_ACCESS_TYPE=1; JSESSIONID=aaaj85MpKF2HUbfaqhs1x; ___rl__test__cookies=1637913084476"); request.setHeader("Host","fanyi.youdao.com"); request.setHeader("Origin","https://fanyi.youdao.com"); request.setHeader("Referer","https://fanyi.youdao.com"); request.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0"); request.setHeader("X-Requested-With","XMLHttpRequest"); CloseableHttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); response.getEntity().getContent().close(); response.close(); return result; } catch (Exception e) { throw e; } } /** * 处理有道翻译结果 * @param json * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static String ydGetResult(String json){ Map<String ,Object> result = JSON.parseObject(json, Map.class); List<List<Map>> res = (List<List<Map>>)result.get("translateResult"); if(!res.isEmpty()){ return res.get(0).get(0).get("tgt")+""; } return null; } /** * 转换请求参数 * @param paramsMap * @return */ private static List<? extends NameValuePair> map2list(Map<String, String> paramsMap) { List<NameValuePair> listParams = new ArrayList<NameValuePair>(); Set<String> keys = paramsMap.keySet(); for (String key : keys) { listParams.add(new BasicNameValuePair(key, paramsMap.get(key))); } return listParams; }
} |
运行结果
谷歌翻译
谷歌翻译需要开启国外代理,网络不通
package fills.tools.translate; import java.util.List; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSON; public class GoogleTranslateTools { public static void main(String[] args) throws Exception{ String en = doGoogleTranslate("测试一下", "zh", "en"); String zh = doGoogleTranslate("test", "en", "zh"); System.out.println(en); System.out.println(zh); } private static CloseableHttpClient httpClient = HttpClients.createDefault(); /** * 封装Goole参数信息 * @param query * @param from zh-CN * @param to en * @return String * @throws Exception */ public static String doGoogleTranslate(String query,String from,String to)throws Exception{ String url = "https://translate.google.com.hk/translate_a/single?"; String urlParam ="client=t&sl="+from+"&tl="+to+"&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&source=btn&ssel=0&tsel=0&kc=0&tk="+getGgJs(query,getGg())+"&q="+query; return ggGetResult(googleTranslate(url+urlParam)); } /** * 封装Goole翻译请求 * @param url * @return String * @throws Exception */ private static String googleTranslate(String url) throws Exception{ try { URIBuilder uri = new URIBuilder(url); HttpGet request = new HttpGet(uri.toString()); request.setHeader("Cookie","NID=511=UKCb40FREknEZtX19ubTXHKnTj2fqh8YZePtu2eWf-ZXdPN_Rs35XiJGF_yjbW2oaSAz4XBJVYOc_2xYAYyQiD3IEoHBJqghUeumnQJdvjn95jqU71b00BtMl2mHwoNiMLYDZgCDBtqU2A5Ql6O3oVMhvGyPrY3CbSsp4kdhzmE; _ga=GA1.3.409789010.1640080107; _gid=GA1.3.27316764.1640080107"); request.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0"); request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); request.setHeader("Origin","https://translate.google.com.hk"); request.setHeader("Referer","https://translate.google.com.hk/"); request.setHeader("X-Requested-With","XMLHttpRequest"); CloseableHttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); response.getEntity().getContent().close(); response.close(); return result; } catch (Exception e) { throw e; } } /** * 处理谷歌翻译结果 * @param json * @return */ @SuppressWarnings({"rawtypes", "unused" }) private static String ggGetResult(String json){ List result = JSON.parseObject(json, List.class); if(!result.isEmpty()){ return ((List)((List)result.get(0)).get(0)).get(0)+""; } return null; } /** * 加载js获取签名信息 * @param query * @param js * @return */ private static String getGgJs(String query,String js){ String res = null; try { ScriptEngine bdToken = new ScriptEngineManager().getEngineByName("js"); bdToken.eval(js); Invocable inv2 = (Invocable) bdToken; res =(String)inv2.invokeFunction("sig",query); } catch (Exception e) { res = null; } return res; }
/** * google 签名 JS * @return String */ private static String getGg(){ StringBuffer gg = new StringBuffer(); gg.append("var sig = function sig(a) { "); gg.append(" var k = ''; "); gg.append(" var b = 406644; "); gg.append(" var b1 = 3293161072; "); gg.append(" "); gg.append(" var jd = '.'; "); gg.append(" var sb = '+-a^+6'; "); gg.append(" var Zb = '+-3^+b+-f'; "); gg.append(" "); gg.append(" for (var e = [], f = 0, g = 0; g < a.length; g++) { "); gg.append(" var m = a.charCodeAt(g); "); gg.append(" 128 > m ? e[f++] = m: (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023), e[f++] = m >> 18 | 240, e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224, e[f++] = m >> 6 & 63 | 128), e[f++] = m & 63 | 128) "); gg.append(" } "); gg.append(" a = b; "); gg.append(" for (f = 0; f < e.length; f++) a += e[f], "); gg.append(" a = RL(a, sb); "); gg.append(" a = RL(a, Zb); "); gg.append(" a ^= b1 || 0; "); gg.append(" 0 > a && (a = (a & 2147483647) + 2147483648); "); gg.append(" a %= 1E6; "); gg.append(" return a.toString() + jd + (a ^ b) "); gg.append("}; "); gg.append(" "); gg.append("function RL(a, b) { "); gg.append(" var t = 'a'; "); gg.append(" var Yb = '+'; "); gg.append(" for (var c = 0; c < b.length - 2; c += 3) { "); gg.append(" var d = b.charAt(c + 2), "); gg.append(" d = d >= t ? d.charCodeAt(0) - 87 : Number(d), "); gg.append(" d = b.charAt(c + 1) == Yb ? a >>> d: a << d; "); gg.append(" a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d "); gg.append(" } "); gg.append(" return a "); gg.append("} "); return gg.toString(); } } |
运行结果
原文地址:https://blog.csdn.net/u014614478/article/details/140637839
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!