Azure tranlate API调用正在返回40100

问题描述 投票:0回答:1

我使用此HTTP-Get请求获取翻译的Bearer令牌:

https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key=1fo8xxx

使用返回的承载,我想使用此API端点翻译短文本:

https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=de

在标题中,我输入:

Content-Type: application/json; charset=UTF-8.

在我体内放这个:

[
   {"Text":"I would really like to drive your car around the block a few times."}
]

我正在使用邮递员,因此在授权选项卡中,我选择了Bearer,并将其插入到它旁边的字段中:

Bearer <result from the first API call>

如果发送请求,我将得到以下结果:

{"error":{"code":401000,"message":"The request is not authorized because credentials are missing or invalid."}}
azure microsoft-cognitive
1个回答
0
投票

您的请求需要“ OCP-Apim-Subscription-Key”标头。看一下官方示例:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
// Install Newtonsoft.Json with NuGet
using Newtonsoft.Json;

/// <summary>
/// The C# classes that represents the JSON returned by the Translator Text API.
/// </summary>
public class TranslationResult
{
    public DetectedLanguage DetectedLanguage { get; set; }
    public TextResult SourceText { get; set; }
    public Translation[] Translations { get; set; }
}

public class DetectedLanguage
{
    public string Language { get; set; }
    public float Score { get; set; }
}

public class TextResult
{
    public string Text { get; set; }
    public string Script { get; set; }
}

public class Translation
{
    public string Text { get; set; }
    public TextResult Transliteration { get; set; }
    public string To { get; set; }
    public Alignment Alignment { get; set; }
    public SentenceLength SentLen { get; set; }
}

public class Alignment
{
    public string Proj { get; set; }
}

public class SentenceLength
{
    public int[] SrcSentLen { get; set; }
    public int[] TransSentLen { get; set; }
}

private const string key_var = "TRANSLATOR_TEXT_SUBSCRIPTION_KEY";
private static readonly string subscriptionKey = Environment.GetEnvironmentVariable(key_var);

private const string endpoint_var = "TRANSLATOR_TEXT_ENDPOINT";
private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var);

static Program()
{
    if (null == subscriptionKey)
    {
        throw new Exception("Please set/export the environment variable: " + key_var);
    }
    if (null == endpoint)
    {
        throw new Exception("Please set/export the environment variable: " + endpoint_var);
    }
    using (var client = new HttpClient())
    using (var request = new HttpRequestMessage())
    {
        // Build the request.
        // Set the method to Post.
        request.Method = HttpMethod.Post;
        // Construct the URI and add headers.
        request.RequestUri = new Uri(endpoint + route);
        request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
        request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

        // Send the request and get response.
        HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
        // Read response as a string.
        string result = await response.Content.ReadAsStringAsync();
        // Deserialize the response using the classes created earlier.
        TranslationResult[] deserializedOutput = JsonConvert.DeserializeObject<TranslationResult[]>(result);
        // Iterate over the deserialized results.
        foreach (TranslationResult o in deserializedOutput)
        {
            // Print the detected input language and confidence score.
            Console.WriteLine("Detected input language: {0}\nConfidence score: {1}\n", o.DetectedLanguage.Language, o.DetectedLanguage.Score);
            // Iterate over the results and print each translation.
            foreach (Translation t in o.Translations)
            {
                Console.WriteLine("Translated to {0}: {1}", t.To, t.Text);
            }
        }
    }
    Console.Read();
}

https://docs.microsoft.com/en-us/azure/cognitive-services/translator/quickstart-translate?pivots=programming-language-csharp

© www.soinside.com 2019 - 2024. All rights reserved.