cle*_*995 1 azure microsoft-cognitive
我使用这个 HTTP-Get 请求来获取翻译的不记名令牌:
https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key=1fo8xxx
Run Code Online (Sandbox Code Playgroud)
使用返回的 Bearer 我想使用这个 API 端点翻译一个短文本:
https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=de
Run Code Online (Sandbox Code Playgroud)
在标题中,我把这个:
Content-Type: application/json; charset=UTF-8.
Run Code Online (Sandbox Code Playgroud)
在正文中,我把这个:
[
{"Text":"I would really like to drive your car around the block a few times."}
]
Run Code Online (Sandbox Code Playgroud)
我正在使用 Postman,所以在授权选项卡中我选择了 Bearer 并在它旁边的字段中插入:
Bearer <result from the first API call>
Run Code Online (Sandbox Code Playgroud)
如果我发送请求,我会得到以下结果:
{"error":{"code":401000,"message":"The request is not authorized because credentials are missing or invalid."}}
Run Code Online (Sandbox Code Playgroud)
小智 6
如果有人偶然发现这一点,经过数小时的反复试验,我发现您需要在标头中传递 Ocp-Apim-Subscription-Region 参数。这是我能够成功运行的python示例。
import json
import requests
def translate(text, source_language, dest_language):
if not <Secret Key>:
return 'Error: the translation service is not configured.'
headers = {'Ocp-Apim-Subscription-Key': <Secret Key>,
'Ocp-Apim-Subscription-Region': <region>,
'Content-type': 'application/json'}
url = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from={}&to={}' \
.format(source_language, dest_language)
body = [{'text': text}]
request = requests.post(url, headers=headers, json=body)
if request.status_code != 200:
return 'Error: the translation service failed.'
return json.loads(request.content.decode('utf-8-sig'))
Run Code Online (Sandbox Code Playgroud)
可以在此处找到区域列表和其他示例:https : //docs.microsoft.com/en-us/azure/cognitive-services/translator/reference/v3-0-reference
不要被未使用该区域的 curl 示例所迷惑。
| 归档时间: |
|
| 查看次数: |
1026 次 |
| 最近记录: |