如何使用Azure在Java或Android中使用Microsoft Translator API

时间:2017-11-02 16:13:18

标签: java c# android azure

我一直在网上搜索几个小时,因为它是Android翻译器文本API的Android或Java的工作示例,因为它是唯一一个每月免费提供2米字符翻译的API。但无济于事,因为我发现的大部分内容自2017年3月起已被弃用,现已迁移到蔚蓝的认知服务,因此无效。谁知道怎么做?我在c#中找到了一个工作代码,它在控制台中输出了转换,但我不能将它自己转换为Java,因为我没有进入C#。 TIA。

以下是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);
        }
    }
}
}

有关弃用的详细信息: https://datamarket.azure.com/dataset/bing/microsofttranslatorspeech

2 个答案:

答案 0 :(得分:2)

您可以通过Microsoft Translator Text API使用REST API

有关详细信息,请参阅此official doc

在这里,我提供了带有java代码的GetTranslations请求的代码段供您参考。

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


    }
}

希望它对你有所帮助。

答案 1 :(得分:1)

另外,要添加@Jay Gongs答案,它会给出翻译文本的完整输出,例如评级,匹配度等。我创建了一个修订版,只显示已翻译的实际文本

关于他上面给出的代码,就在代码

下面

的System.out.println(RESP);

删除或评论上述代码,并在其下方添加以下行。

var config = require('./config/config.js');
var net = require('net');
var timer = require('./timer.js');

const server = require('net').createServer({ pauseOnConnect: true });
const child = require('child_process').fork('anotherProcess.js', ['child']);

server.on('connection', function(socket) {
    child.send('socket', socket);
});

server.listen(config.proxy.port, function() {
    console.log((new Date()) + ' Server is listening on port ' + 
config.proxy.port);
});

server.on('error', function(err) {
    if (err.code === 'EADDRINUSE') {
        console.log('Address in use, retrying...');
        setTimeout(function() {
            server.close();
            server.listen(config.proxy.port);
        }, 1000);
    }
});