如何在Android中使用Microsoft Translator API [英] How to use Microsoft Translator API in Android

查看:143
本文介绍了如何在Android中使用Microsoft Translator API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自2017年3月以来,已经弃用了针对Android示例的Microsoft Translator API(仅此一年)。所以我很难在android上翻译文本。任何人都可以帮我在android上做这个工作吗?只是我已经在java中使用它,但我无法在Android上运行它。我已经尝试过使用asynctask,但无济于事,没有翻译出来。或者我刚刚做了一个错误的asyc任务?。

The Microsoft Translator API for android samples has already been deprecated since march 2017 (just this yr). So I'm having a hard time translating text on android. Can anyone help me make this work on android?. It's just that I already have this working in java but I can't make it work on Android. I already tried using asynctask , but to no avail, no translation is being outputed. Or prolly I just did a wrong asyc task?.

应用程序的界面是这样的:

The Interface of the application is like this:

它只有一个简单的文本字段应在其他文本字段中输出的翻译。翻译是从韩语到英语。

It just have a simple textfield with translation that should be outputed on the other textfield. The translation is from Korean to English.

Github项目文件在这里

Github Project File is in here

https://github.com/iamjoshuabcxvii/MSTranslateAPIforAndroid

Android代码就是这样。

Android code is this.

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import org.apache.commons.io.IOUtils;

import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;


public class MainActivity extends AppCompatActivity {

//MS Translator Key is in here
public static String key = "<The MS Assigned Translator Key>";
private TextView txtTranslatedText, txtOriginalText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtOriginalText = findViewById(R.id.txtOriginalText);
    txtTranslatedText = findViewById(R.id.txtTranslatedText);


}


public void translate(View view) {
//        String textOrig = txtOriginalText.getText().toString();
//        String textOrig ="안녕하세요 123 -)^ 친구";
        String textOrig;
        textOrig=txtOriginalText.getText().toString();
        String output;
    output=getTranslation(textOrig);
    txtTranslatedText.setText(output);
}


public static String getTranslation(String translatedTextStr) {


    try {
        // Get the access token
        // The key got from Azure portal, please see https://docs.microsoft.com/en-us/azure/cognitive-services/cognitive-services-apis-create-account
        String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
        HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
        authConn.setRequestMethod("POST");
        authConn.setDoOutput(true);
        authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
        IOUtils.write("", authConn.getOutputStream(), "UTF-8");
        String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");
//            System.out.println(token);  //Code to Display Token

//          Using the access token to build the appid for the request url
            String appId = URLEncoder.encode("Bearer " + token, "UTF-8");
            String text = URLEncoder.encode(translatedTextStr, "UTF-8");
            String from = "ko";
            String to = "en";
            String translatorTextApiUrl = String.format("https://api.microsofttranslator.com/v2/http.svc/GetTranslations?appid=%s&text=%s&from=%s&to=%s&maxTranslations=5", appId, text, from, to);
            HttpsURLConnection translateConn = (HttpsURLConnection) new URL(translatorTextApiUrl).openConnection();
            translateConn.setRequestMethod("POST");
            translateConn.setRequestProperty("Accept", "application/xml");
            translateConn.setRequestProperty("Content-Type", "text/xml");
            translateConn.setDoOutput(true);
            String TranslationOptions = "<TranslateOptions xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">" +
                    "<Category>general</Category>" +
                    "<ContentType>text/plain</ContentType>" +
                    "<IncludeMultipleMTAlternatives>True</IncludeMultipleMTAlternatives>" +
                    "<ReservedFlags></ReservedFlags>" +
                    "<State>contact with each other</State>" +
                    "</TranslateOptions>";
            translateConn.setRequestProperty("TranslationOptions", TranslationOptions);
            IOUtils.write("", translateConn.getOutputStream(), "UTF-8");
            String resp = IOUtils.toString(translateConn.getInputStream(), "UTF-8");

//            System.out.println(resp+"\n\n");
            String s=resp;
            Pattern assign_op=Pattern.compile("(<TranslatedText>)"
                    + "|(<\\/TranslatedText>)"
                    + "|[()\\\\[\\\\]{};=#.,'\\\\^:@!$%&_`*-<>]"
                    + "|[a-zA-Z0-9\\s]*"
                    + "");
            Matcher m = assign_op.matcher(s) ;

        String actualTranslation="";
        Boolean endOfTransTxt=false,startOfTransTxt=false,concat=false;
        String foundRegexStr="",tempStr="";

        while (m.find()) {
            foundRegexStr=m.group();

            if(m.group().matches("(<TranslatedText>)"))  {
                startOfTransTxt=true;
            }
            else if(m.group().matches("(<\\/TranslatedText>)"))    {
                endOfTransTxt=true;
                concat=false;
            }
            else{
                startOfTransTxt=false;
                endOfTransTxt=false;
            }

            if(startOfTransTxt==true)  {
                concat=true;
            }
            else if(concat==true) {
                tempStr=tempStr+""+m.group();
            }
            else   {

            }
        }
//    System.out.println("\nTranslated Text:  "+tempStr);
            translatedTextStr=tempStr;


    } catch (Exception e) {
        e.printStackTrace();
    }

    return translatedTextStr;
}


}


推荐答案

我认为你做错了 AsyncTask
您可以这样做:

I think you did a wrong AsyncTask. You can do it like this:

private class TransAsynTask extends AsyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... strings) {
        String output = getTranslation(strings[0]);
        return output;
    }

    @Override
    protected void onPostExecute(String s) {
        txtTranslatedText.setText("Output: " + s);
        super.onPostExecute(s);
    }
}

并且在 onCreate 你打电话:

    String textOrig;
    textOrig = txtOriginalText.getText().toString();

    new TransAsynTask().execute(textOrig);

    /*String output;
    output = getTranslation(textOrig);
    txtTranslatedText.setText("Translated Text: " + output);*/

这篇关于如何在Android中使用Microsoft Translator API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆