如何使用带有授权令牌的天蓝色翻译器?

How to use azure translator with authorization token?

我想通过授权令牌使用 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 分钟。对翻译器进行多次调用时,应重用令牌。但是,如果您的程序在很长一段时间内向翻译器发出请求,那么您的程序必须定期(例如,每 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

详情请参考here and here