java - Microsoft Translator API Java,如何使用 Azure 获取客户端新 ID

标签 java azure clientid

Translate.setClientId("某事"); Translate.setClientSecret("something1");

我之前曾使用以下语法成功运行过我的代码,但是,50% 的情况下我会收到一条错误消息:TranslateApiException:找不到与请求凭据关联的 Activity Azure Market Place Translator 订阅。 :

我通过 Microsoft 使用的旧网站订阅了我的应用程序,但我认为出现问题是因为他们使用的是 Azure。现在,我已经通过 Azure 订阅了我的应用程序,并且订阅了 Microsoft Translator API 服务。想知道如何将其设置为 Azure 提供的新 ClientID、ClientSecret。

这是我首先订阅的“旧”网站: https://datamarket.azure.com/home/

最佳答案

如旧官方网站的信息(翻译者 speech & text api) & Announcements表示,“微软翻译 API 现已在 Azure 门户上提供”和“需要在 2017 年 4 月 30 日之前采取行动 - 微软翻译迁移到 Azure”。所以如果你现在想使用 Translator API,你需要有 Azure 订阅并创建一个 Azure Cognitive 服务的 Translator 帐户,如官方 tutorial说。

例如,使用文本翻译 API,您可以遵循新的 tutorial获取访问 token 来为 API 构建 appid,如下面的 Java 示例代码。

// 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 key = "<your translator account key>";
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("happy birthday", "UTF-8");
String from = "en";
String to = "fr";
String translatorTextApiUrl = String.format("https://api.microsofttranslator.com/v2/http.svc/Translate?appid=%s&text=%s&from=%s&to=%s", appId, text, from, to);
HttpsURLConnection translateConn = (HttpsURLConnection) new URL(translatorTextApiUrl).openConnection();
translateConn.setRequestMethod("GET");
translateConn.setRequestProperty("Accept", "application/xml");
String resp = IOUtils.toString(translateConn.getInputStream(), "UTF-8");
System.out.println(resp);

希望有帮助。如有任何疑问,请随时告诉我。

关于java - Microsoft Translator API Java,如何使用 Azure 获取客户端新 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42891510/

相关文章:

Java while循环永远不会进入循环

.net - 将 Windows 服务移植到 Windows Azure

sql-server - Azure Maps 和 SQL AT TIME ZONE 夏威夷时区不兼容

Azure 事件中心通过分区进行流分析

jquery - 处理 ASP.NET 的 ClientID 的最佳方法是什么

java - 在 Android 应用程序中使用 Json

java - 如何使用 RTFEditorKit 读取页眉和页脚行

java - 返回指定用户提交的所有更改列表 - Perforce Java API

ajax - 如何从#{cc.clientId} 中提取第一个组件 ID?

authentication - 为什么 OAuth2 密码授予流程需要客户端 ID?