如何使用带有授权令牌的 azure 翻译器?

问题描述

我想使用带有授权令牌的 azure 翻译服务。有很多资源解释了如何使用订阅密钥进行操作,但我找不到任何解释授权令牌使用的资源。我可以获得授权令牌,但是当我用它发送请求时,响应状态代码是 401。 这是我发送请求的方式:

curl POST 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer token' \
--data-raw '[{'\''Text'\'':'\''Hello World!'\''}]'

解决方法

如果您想使用身份验证令牌调用文本翻译API,请参考以下步骤

  1. 获取令牌。如果您的服务是全球性的,则端点为 https://api.cognitive.microsoft.com/sts/v1.0/issueToken
curl -v -X POST \
"https://YOUR-REGION.api.cognitive.microsoft.com/sts/v1.0/issueToken" \
-H "Content-type: application/x-www-form-urlencoded" \
-H "Content-length: 0" \
-H "Ocp-Apim-Subscription-Key: YOUR_SUBSCRIPTION_KEY"

此外,请注意身份验证令牌的有效期为 10 分钟。多次调用 Translator 时,应重用令牌。但是,如果您的程序在很长一段时间内向翻译器发出请求,则您的程序必须定期(例如,每 8 分钟)请求一个新的访问令牌。

  1. 调用 API
curl -X POST 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en&to=de' \
-H 'Authorization: Bearer YOUR_AUTH_TOKEN' \
-H 'Content-Type: application/json' \
--data-raw '[{ "text": "How much for the cup of coffee?" }]' | json_pp

enter image description here enter image description here

有关详细信息,请参阅 herehere