Azure перевод вызова API-интерфейса translate и 40100 - PullRequest
0 голосов
/ 06 апреля 2020

Я использовал этот запрос HTTP-Get для получения токена Bearer для перевода:

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

Используя возвращенный Bearer, я хотел перевести короткий текст, используя эту конечную точку 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."}}

1 Ответ

0 голосов
/ 06 апреля 2020

Для вашего запроса требуется заголовок "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

...