Microsoft translation Interface

Source: Internet
Author: User
Tags textout

Some time ago, I made an android project. Because it was an international project, I could only find a translation website for manual translation. However, there were too many content and manual operations, which made me feel inefficient, therefore, I am a little lazy. I want to write a program and translate it automatically.

After several times, Google and Du Niang found that there were two translation interfaces, Google and Microsoft. Later, they found that Google's translation interfaces were not free of charge, in addition, access is restricted when APIs are often called. Therefore, only Microsoft can be used. Microsoft interfaces are also charged, but there is a limit on the number of translation content.

The following are the translation links provided by the two companies. I am also very lazy in English and cannot fully explain them. If you need comprehensive information, visit the official website.

Google Translate: https://developers.google.com/translate? Hl = ZH-CN

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

Foreign Internet companies have a little bit of conscience. At least they are making money and giving back to the society at the same time. There is no such service website in China ).

The following briefly describes how to use Java to access the Microsoft translation interface and translate strings.

To use Microsoft's translation interface, you must first register Microsoft's marketplace and then enter the release soft name to get a software name and a key respectively, this is basically the same as the current mode of various advertising platforms and third-party interfaces.

Before using the translation interface, send a request, submit your name and key, get the token, add the token to the content to be translated, and finally get the translated content.

Since a POST request must be used to obtain the token, the returned data is JSON, so when using it, the third-party jar package, commons-httpclient.jar, commons-logging-1.0.4.jar, org. JSON. jar.

The following is the code:

1. The first part reads the local configuration, including the name, key, language types supported by Microsoft (38, really powerful,), and the content to be translated.

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();}}


Enter the name and key of your software in the xxx area above.

2. Enable the thread pool and use the thread pool to send requests and translate data. The translation speed is really fast ,.

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. translated code

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;}

The core code for the above translation is to send a GET request using the URL parameter passing technology, but before the request, it must be encoded first, otherwise there will be an error. When I use it, this error occurs.

For example, it is okay to translate hello. If you translate Welcome to China. Then there will be a problem, because there is a space in the middle, of course, there cannot be a space in the URL, so you must encode it first.


For example, if I translate loading and get the data content, this is the case.

<String xmlns = "http://schemas.microsoft.com/2003/10/Serialization/"> loading. </String>

Remove all the labels in XML to get the translation structure.

body = body.replaceAll("<([^>]*)>", "")

Finally, use the future in Java to call the callback when all tasks are completed.

public interface OnTranslateCallback {public void onTranslate(int current, int count);public void onComplete(List<TextOut> outs);}


Okay. You can close the job. If you have any questions, thank you for your guidance.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.