gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 08:24:06 28 4
gpt4 key购买 nike

我已经在网上搜索了几个小时,寻找 Microsoft 文本翻译 API 的 Android 或 Java 工作示例,因为它是唯一每月免费提供 200 万个字符翻译的 API。但没有任何效果,因为我发现的大部分内容自 2017 年 3 月以来已被弃用,并且现在已迁移到 azure 认知服务。有谁知道该怎么做吗?我在 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

最佳答案

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

请引用此official doc了解更多详情。

这里我提供了GetTranslations请求的java代码 fragment ,供大家引用。

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://learn.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();
}


}
}

希望对您有帮助。

关于java - 如何使用 Azure 在 Java 或 Android 中使用 Microsoft Translator API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47079895/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com