[置顶] 微软翻译接口

前些时候,做个了Android项目,由于是需要国际化,只能找个翻译网站手动翻译下,但是内容实在太多,而且纯手动的操作,感觉效率地下,所以偷了个懒,想写个程序,自动翻译下。

经过若干次谷歌和度娘,发现提供翻译接口的有2家,一个是google的,还有个就是microsoft,后来发现google的翻译接口,不是免费的,而且经常调用接口就会限制访问,所以就只能用微软的,微软的接口也是要收费的,不过有个翻译内容数量的限制。

下面是两家提供翻译的连接,本人英语也很懒,不能说的很全面,如果需要全面的资料还是浏览官方的网站吧。

Google Translate:https://developers.google.com/translate/?hl=zh-CN

Microsoft Translate:http://msdn.microsoft.com/en-us/library/dd576287.aspx

外国的互联网公司稍微有点良知,最起码在赚钱的同时,也同时回馈了社会,国内简直没有提供这样服务的网站(这里不爽的吐槽下)。

下面简简述用Java访问微软翻译接口,翻译字符串的方法。

要使用微软的翻译接口,必须首先注册微软的Marketplace,然后填写发布软的名称,分别得到一个软件名称和一个key,这个基本上和现在各个广告平台和第三方接口的模式差不多。

在使用翻译的接口前,发送请求,提交你的名称和key,然后得到token,然后在发送需要翻译的内容加token,最后得到的就是翻译后的内容。

由于在获取token的时候,必须使用post请求,返回的数据是json,所以在使用的时候,额外引用了第三方jar包,commons-httpclient.jar、commons-logging-1.0.4.jar、org.json.jar等。

下面是代码部分:

1、第一部分读取本地配置,包括名称、key、微软支持的语种类型(38种,真的很强大,羡慕),以及需要翻译的内容。

private void getTokenFromMs() throws HttpException, IOException {
		MCLog.i("Begin to get token.");
		HttpClient client = new HttpClient();
		PostMethod postMethod = new PostMethod("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13");
		postMethod.addParameter("grant_type", "client_credentials");
		postMethod.addParameter("client_id", "xxx");
		postMethod.addParameter("client_secret", "xxxxxxxx");
		postMethod.addParameter("scope", "http://api.microsofttranslator.com");
		client.executeMethod(postMethod);
		String body = postMethod.getResponseBodyAsString();
		try {
			JSONObject jsonObj = new JSONObject(body);
			tokenText = jsonObj.getString("access_token");
			MCLog.i("Success get token.");
			MCLog.i("token = %s .", tokenText);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}


上面的xxx的地方写上自己的软件的名称和key。

2、开启线程池,使用线程池来发送请求,翻译数据,翻译的速度真的很快,大笑

		Properties pro = I18n.getInstance().getProperties();
		ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 5);
		CompletionService<TextOut> completionService = new ExecutorCompletionService<TextOut>(executorService);
		Iterator<Object> iterator = pro.keySet().iterator();
		int cout = 0;
		while (iterator.hasNext()) {
			final String key = iterator.next().toString();
			completionService.submit(new Callable<TextOut>() {
				public TextOut call() throws Exception {
					Translator translate = new Translator();
					TextOut ce = translate.translate("en", key, in.getEneitys());
					return ce;
				}
			});
			cout++;
		}
		for (int i = 0; i < cout; i++) {
			TextOut ce = null;
			try {
				ce = completionService.take().get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
			if (ce != null) {
				onTranslate(ce);
			}
		}
3、翻译的代码

public synchronized TextOut translate(String from, String to, List<Entity> entitys) {
		if (token == null) {
			throw new RuntimeException("Token is null.");
		}
		list.clear();
		MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
		HttpClient client = new HttpClient(manager);
		HttpMethod getMethod = null;
		for (Entity e : entitys) {
			String name = e.getName();
			String text = e.getText();

			String url = "http://api.microsofttranslator.com/v2/Http.svc/Translate?From={0}&To={1}&Text={2}";
			MessageFormat message = new MessageFormat(url);
			try {
				url = message.format(new Object[] { URLEncoder.encode(from, "utf-8"), URLEncoder.encode(to, "utf-8"), URLEncoder.encode(text, "utf-8") });
				getMethod = new GetMethod(url);
				getMethod.addRequestHeader("Authorization", authorization);
				client.executeMethod(getMethod);
				String body = getMethod.getResponseBodyAsString();
				getMethod.releaseConnection();

				Entity entity = new Entity(name, body.replaceAll("<([^>]*)>", ""));
				list.add(entity);
				MCLog.i("Translate %s is completing in %s.", name, to);
			} catch (HttpException ex) {
				ex.printStackTrace();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		TextOut out = new TextOut(to, list);
		if (onTranslateCompleteCallback != null) {
			onTranslateCompleteCallback.onTranslateCompleteCallback(out);
		}
		return out;
	}

上面翻译的核心代码就是发送一个get请求,使用url传参技术,但是在请求前,必须先编码,不然会有错误,我在使用的时候,就出现过这样的错误。

比如翻译hello是没有问题的,如果翻译welcome to china。那么就会出现问题,因为中间有空格,在url中当然不能出现空格了,所以必须先编码下。难过


比如我翻译loading,得到数据内容是这样的。

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">正在加载。</string>
然后把xml的标签全部去掉,就得到翻译的结构了。
body = body.replaceAll("<([^>]*)>", "")

最后使用Java中的Future,当所有的任务完成的时候,调用回调。

public interface OnTranslateCallback {

		public void onTranslate(int current, int count);

		public void onComplete(List<TextOut> outs);
	}

好的,打完收工, 大笑,如有问题,欢迎指导。


转载于:https://www.cnblogs.com/liushuibufu/p/3253610.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值