免费调用谷歌翻译

最近公司有需求,需要调用谷歌翻译的接口。虽然我最后可以勉强实现了翻译的功能,但还是把这个方法记录下来供各位参考。

首先声明,我这种实现方法只能翻译少量的内容,如果想要翻译比较多的内容就只能把内容拆分开来翻译。

1.找到谷歌翻译,通过f12查看谷歌翻译的时候调用的接口:https://translate.google.cn/translate_a/single?client=t&sl=auto&tl=en&hl=zhCN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF8&oe=UTF8&ssel=0&tsel=3&kc=0&tk=80338.476099&q=%E4%BB%96%E4%BB%AC%E8%BF%99%E6%A0%B7%E8%AF%B4

解析开来就是:client=t、sl=auto、tl=toLanguage、hl=fromLanguage、da=at、dt=bd、dt=ex、dt=ld、dt=gca、dt=rw、dt=rm、dt=ss、dt=t、ie=UTF8、oe=UTF8、ssel=0、tsel=3、kc=0、tk=(需要经过js文件的计算)、q=(需要翻译的文字)

这么多参数中只有tk参数最麻烦,需要使用经过js文件的计算得到,js文件我会在文章最后面分享。

2.使用jsoup模拟浏览器发送请求,接收到返回信息并解析返回信息,得到翻译的结果。(注意:一定要给请求中间加一条sleep(1000),否则谷歌可能会封你得ip)

//谷歌翻译(只能翻译比较短的内容)Get
	public static String TranslateGoogleGet(String transalteContente,String fromLanguage,String toLanguage){
		StringBuilder result=new StringBuilder();
		StringBuilder url=new StringBuilder();
		try {
			url.append("https://translate.google.cn/translate_a/single?").append("client=t&sl=").append(fromLanguage)
			.append("&tl=").append(toLanguage).append("&hl=zh-CN").append("&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw")
			.append("&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&otf=2&ssel=0&tsel=0&kc=1&tk=").append(googleToken(transalteContente)).append("&q=")
			.append(URLEncoder.encode(transalteContente, "utf-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		//获取请求连接
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String resp;
		try {
			resp = HttpUtil.doGet(url.toString());
			if("Error Response:caused by-->connect timed out".equals(resp) || "Error Response:caused by-->Read timed out".equals(resp)
					||"Error Response: HTTP/1.1 503 Service Unavailable".equals(resp)){
				return "error";
			}
			String string = resp.split("]],")[0];
			String[] split = string.split(",null,null,3],");
			for (String string2 : split) {
				if(!string2.contains("[null,null,")){
					String string3 = string2.split("\",\"")[0];
					int start = string3.indexOf("\"")+1;
					result.append(string3.substring(start,string3.length()));
				}
			}
			/*int start = resp.indexOf("\"")+1;
			int end = resp.indexOf("\"", start+1);*/
			/*String[] split = resp.split("]],")[0].replace("[[[", "[").split("],");
			for (String string : split) {
				String replace = string.split(",")[0].replace("[", "").replace("\"", "");
				if(replace!=null && !"null".equals(replace)){
					result.append(replace);
				}
			}*/
			return result.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

 

/**
	 * 获取谷歌翻译的tk值
	 * @param text
	 * @return
	 */
	 private static String googleToken(String text) {
	        String tk = "";
	        ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
	        try {
	        	//FileReader reader = new FileReader(ConfigUtil.getString("GoogleJs"));
	        	URL resource = TranslateUtil.class.getResource("");
	    		String string = resource.getPath().split("/WEB-INF")[0];
	    		string=string+"/gmphtml/js/Google.js";
	        	FileReader reader = new FileReader(string);
	            engine.eval(reader);
	            if (engine instanceof Invocable) {
	                Invocable invoke = (Invocable)engine;
	                tk = String.valueOf(invoke.invokeFunction("token", text));
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return tk;
	    }   }

Google.js文件分享:链接:https://pan.baidu.com/s/13HCY0T3BvI9zwQNEzyq0Yw 密码:pow2

 

 

 

 

 

你可能感兴趣的:(免费调用谷歌翻译)