简体   繁体   中英

How to use Microsoft Translator API in Java or Android using Azure

I have been searching the web for hours now for a working sample in Android or java of the Microsoft Translator Text API since its the only API with free 2m character translation everymonth. But to no avail, none works since most of what I find are already deprecated since this march 2017 and had been migrated to the azure cognitive services now. Anyone knows how to do it?. I found a working code in c# which outputs the translation in console, but I can't convert it myself to Java since I'm not into C#. TIA.

Below is the working code in C#.

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace AzureSubscriptionKeySample
{
    class Program
    {
        /// Header name used to pass the subscription key to translation service
        private const string OcpApimSubscriptionKeyHeader = "Ocp-Apim-Subscription-Key";

    /// Url template to make translate call
    private const string TranslateUrlTemplate = "http://api.microsofttranslator.com/v2/http.svc/translate?text={0}&from={1}&to={2}&category={3}";

    private const string AzureSubscriptionKey = "MyAzureSubscriptionKey";   //Enter here the Key from your Microsoft Translator Text subscription on http://portal.azure.com

    static void Main(string[] args)
    {
        TranslateAsync().Wait();
        Console.ReadKey();
    }

    /// Demonstrates Translate API call using Azure Subscription key authentication.
    private static async Task TranslateAsync()
    {
        try
        {
            var translateResponse = await TranslateRequest(string.Format(TranslateUrlTemplate, "안녕하세요 친구", "ko", "en", "general"), AzureSubscriptionKey);
            var translateResponseContent = await translateResponse.Content.ReadAsStringAsync();
            if (translateResponse.IsSuccessStatusCode)
            {
                Console.WriteLine("Translation result: {0}", translateResponseContent);
            }
            else
            {
                Console.Error.WriteLine("Failed to translate. Response: {0}", translateResponseContent);
            }
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine("Failed to translate. Exception: {0}", ex.Message);
        }
    }

    public static async Task<HttpResponseMessage> TranslateRequest(string url, string azureSubscriptionKey)
    {
        using (HttpClient client = new HttpClient())
        { 
            client.DefaultRequestHeaders.Add(OcpApimSubscriptionKeyHeader, azureSubscriptionKey);
            return await client.GetAsync(url);
        }
    }
}
}

Details about Deprecation: https://datamarket.azure.com/dataset/bing/microsofttranslatorspeech

You could use the Microsoft Translator Text API via REST API .

Please refer to this official doc for more details.

Here, I offer snippet code of GetTranslations request with java code for your reference.

import org.apache.commons.io.IOUtils;

import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Test1 {
    private static String key = "<your translator account key>";

    public static void main(String[] args) {
        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);

//          Using the access token to build the appid for the request url
            String appId = URLEncoder.encode("Bearer " + token, "UTF-8");
            String text = URLEncoder.encode("Hello", "UTF-8");
            String from = "en";
            String to = "fr";
            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);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

Hope it helps you.

Also, to add to @Jay Gongs answer which give the complete output of the translated text like rating, match degree etc. I created an revision in that that will only show the actual text that was translated

On the code he gave above, just below the code


System.out.println(resp);


Delete or comment the above code and add the following lines below it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM