Share via


Azure AI 번역기 API 사용

이 방법 가이드에서는 Translator 서비스 REST API를 사용하는 방법을 알아봅니다. 기본 예제로 시작하여 개발 중에 일반적으로 사용되는 다음과 같은 몇 가지 핵심 구성 옵션으로 이동합니다.

필수 조건

  • Azure 구독 - 체험 구독 만들기

  • Azure AI 다중 서비스 또는 Translator 리소스. Azure 구독이 있으면 Azure Portal에서 단일 서비스 또는 다중 서비스 리소스를 만들어 키와 엔드포인트를 가져옵니다. 배포 후 리소스로 이동을 선택합니다.

  • 체험 가격 책정 계층(F0)을 통해 서비스를 사용해 보고, 나중에 프로덕션을 위한 유료 계층으로 업그레이드할 수 있습니다.

  • 만든 리소스의 키와 엔드포인트는 애플리케이션을 Translator 서비스에 연결하는 데 필요합니다. 나중에 키와 엔드포인트를 코드 샘플에 붙여넣습니다. Azure Portal 키 및 엔드포인트 페이지에서 다음 값을 찾을 수 있습니다.

    Screenshot: Azure portal keys and endpoint page.

Important

완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 Azure Key Vault와 같은 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용합니다. 자세한 내용은 Azure AI 서비스 보안을 참조하세요.

헤더

REST API를 통해 Translator 서비스를 호출하려면 다음 헤더가 각 요청에 포함되어 있는지 확인해야 합니다. 걱정하지 마세요! 다음 섹션에서 헤더가 샘플 코드에 포함됩니다.

헤더 조건
Ocp-Apim-Subscription-Key Azure Portal의 Translator 서비스 키입니다.
  • Required
Ocp-Apim-Subscription-Region 리소스를 만든 지역입니다.
  • Azure AI 다중 서비스 또는 미국 서부와 같은 지역(지리적) 리소스를 사용하는 경우 필수입니다.
  • 단일 서비스 번역기 리소스를 사용하는 경우 선택 사항입니다.
Content-Type 페이로드의 콘텐츠 형식입니다. 허용되는 값은 application/json 또는 charset=UTF-8입니다.
  • Required
Content-Length 요청의 길이 본문입니다.
  • 선택 사항
X-ClientTraceId 요청을 고유하게 식별하는 클라이언트 생성 ID입니다. ClientTraceId라는 쿼리 매개 변수를 사용하는 쿼리 문자열에서 추적 ID를 포함하는 경우 이 헤더를 생략할 수 있습니다.
  • 선택 사항

애플리케이션 설정

  1. 현재 버전의 Visual Studio IDE가 있는지 확인합니다.

    Visual Studio를 처음 사용하는 경우 Visual Studio 소개 Learn 모듈을 사용해 보세요.

  2. Visual Studio를 엽니다.

  3. 시작 페이지에서 새 프로젝트 만들기를 선택합니다.

    Screenshot: Visual Studio start window.

  4. 새 프로젝트 만들기 페이지의 검색 상자에서 콘솔을 입력합니다. 콘솔 애플리케이션 템플릿을 선택하고, 다음을 선택합니다.

    Screenshot: Visual Studio's create new project page.

  5. 새 프로젝트 구성 대화 상자 창의 [프로젝트 이름] 상자에서 translator_text_app를 입력합니다. "동일한 디렉터리에 솔루션 및 프로젝트 배치" 확인란을 선택 취소한 상태로 두고 다음을 선택합니다.

    Screenshot: Visual Studio's configure new project dialog window.

  6. 추가 정보 대화 상자 창에서 .NET 6.0(장기 지원)이 선택되어 있는지 확인합니다. "최상위 문 사용 안 함" 확인란을 선택 취소하고 만들기를 선택합니다.

    Screenshot: Visual Studio's additional information dialog window.

NuGet을 사용하여 Newtonsoft.json 패키지 설치

  1. translator_quickstart 프로젝트를 마우스 오른쪽 단추로 클릭하고 NuGet 패키지 관리...를 선택합니다.

    Screenshot of the NuGet package search box.

  2. 찾아보기 탭을 선택하고 Newtonsoft를 입력합니다.

    Screenshot of the NuGet package install window.

  3. 오른쪽 패키지 관리자 창에서 설치를 선택하여 프로젝트에 패키지를 추가합니다.

    Screenshot of the NuGet package install button.

애플리케이션 빌드

참고 항목

  • .NET 6부터 console 템플릿을 사용하는 새 프로젝트는 이전 버전과 다른 새 프로그램 스타일을 생성합니다.
  • 새 출력에서는 작성해야 하는 코드를 간소화하는 최신 C# 기능을 사용합니다.
  • 최신 버전을 사용하는 경우 Main 메서드 본문을 작성하기만 하면 됩니다. 최상위 문, 전역 using 지시문 또는 암시적 using 지시문을 포함할 필요가 없습니다.
  • 자세한 내용은 최상위 문을 생성하는 새 C# 템플릿을 참조하세요.
  1. Program.cs 파일을 엽니다.

  2. Console.WriteLine("Hello World!") 줄을 포함하여 기존 코드를 삭제합니다. 코드 샘플을 복사하여 애플리케이션의 Program.cs 파일에 붙여넣습니다. 각 코드 샘플에 대해 Azure Portal Translator 인스턴스의 값으로 키 및 엔드포인트 변수를 업데이트해야 합니다.

  3. 애플리케이션에 원하는 코드 샘플을 추가한 후 formRecognizer_quickstart 옆에 있는 녹색 시작 단추를 선택하여 프로그램을 빌드하고 실행하거나 F5를 누릅니다.

Screenshot of the run program button in Visual Studio.

Important

이 가이드의 샘플에는 하드 코딩된 키와 엔드포인트가 필요합니다. 완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 자격 증명을 안전하게 저장하고 액세스하는 방법을 사용하는 것이 좋습니다. 자세한 내용은 Azure AI 서비스 보안을 참조하세요.

텍스트 번역

Translator 서비스의 핵심 작업은 텍스트를 번역하는 것입니다. 이 섹션에서는 단일 원본(from)을 가져와서 두 개의 출력(to)을 제공하는 요청을 작성합니다. 그런 다음, 요청과 응답을 모두 조정하는 데 사용할 수 있는 몇 가지 매개 변수를 검토합니다.

using System.Text;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
    // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    private static readonly string location = "<YOUR-RESOURCE-LOCATION>";

    static async Task Main(string[] args)
    {
        // Input and output languages are defined as parameters.
        string route = "/translate?api-version=3.0&from=en&to=sw&to=it";
        string textToTranslate = "Hello, friend! What did you do today?";
        object[] body = new object[] { new { Text = textToTranslate } };
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", key);
            // location required if you're using a multi-service or regional (not global) resource.
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);

            // 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();
            Console.WriteLine(result);
        }
    }
}

성공적으로 호출되면 다음과 같은 응답이 표시됩니다.

[
   {
      "translations":[
         {
            "text":"Halo, rafiki! Ulifanya nini leo?",
            "to":"sw"
         },
         {
            "text":"Ciao, amico! Cosa hai fatto oggi?",
            "to":"it"
         }
      ]
   }
]

response headers: x-metered-usage 필드에서 각 요청에 대한 사용량(요금 청구된 문자 수)을 확인할 수 있습니다.

언어 검색

번역이 필요하지만 텍스트의 언어를 모르는 경우 언어 감지 작업을 사용할 수 있습니다. 원본 텍스트 언어를 식별하는 방법은 여러 가지가 있습니다. 이 섹션에서는 translatedetect 엔드포인트를 사용하여 언어 감지를 사용하는 방법에 대해 알아봅니다.

번역 중 원본 언어 감지

번역 요청에 from 매개 변수를 포함하지 않으면 Translator 서비스가 원본 텍스트의 언어를 검색하려고 시도합니다. 응답에서 감지된 언어(language)와 신뢰도 점수(score)를 얻을 수 있습니다. score1.0에 가까울수록 감지가 정확하다는 신뢰도가 높아집니다.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    private static readonly string location = "<YOUR-RESOURCE-LOCATION>";

    static async Task Main(string[] args)
    {
        // Output languages are defined as parameters, input language detected.
        string route = "/translate?api-version=3.0&to=en&to=it";
        string textToTranslate = "Halo, rafiki! Ulifanya nini leo?";
        object[] body = new object[] { new { Text = textToTranslate } };
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            // location required if you're using a multi-service or regional (not global) resource. 
            request.Headers.Add("Ocp-Apim-Subscription-Key", key);
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);

            // 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();
            Console.WriteLine(result);
        }
    }
}

성공적으로 호출되면 다음과 같은 응답이 표시됩니다.

[
   {
      "detectedLanguage":{
         "language":"sw",
         "score":0.8
      },
      "translations":[
         {
            "text":"Hello friend! What did you do today?",
            "to":"en"
         },
         {
            "text":"Ciao amico! Cosa hai fatto oggi?",
            "to":"it"
         }
      ]
   }
]

번역 없이 원본 언어 감지

번역을 수행하지 않고도 Translator 서비스를 사용하여 원본 텍스트의 언어를 감지할 수 있습니다. 이렇게 하려면 /detect 엔드포인트를 사용합니다.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    private static readonly string location = "<YOUR-RESOURCE-LOCATION>";

    static async Task Main(string[] args)
    {
        // Just detect language
        string route = "/detect?api-version=3.0";
        string textToLangDetect = "Hallo Freund! Was hast du heute gemacht?";
        object[] body = new object[] { new { Text = textToLangDetect } };
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", key);
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);

            // 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();
            Console.WriteLine(result);
        }
    }
}

/detect 엔드포인트 응답에는 대체 검색이 포함되며 검색된 모든 언어에 대해 번역 및 음역이 지원되는지 여부를 나타냅니다. 성공적으로 호출되면 다음과 같은 응답이 표시됩니다.

[
   {
      "language":"de",

      "score":1.0,

      "isTranslationSupported":true,

      "isTransliterationSupported":false
   }
]

음역 텍스트

음역은 발음 유사성을 기반으로 하여 단어 또는 구를 한 언어의 스크립트(알파벳)에서 다른 언어로 변환하는 과정입니다. 예를 들어 음역을 사용하여 "สวัสดี"(thai)를 "sawatdi"(latn)로 변환할 수 있습니다. 음역을 수행하는 방법은 여러 가지가 있습니다. 이 섹션에서는 translatetransliterate 엔드포인트를 사용하여 언어 감지를 사용하는 방법에 대해 알아봅니다.

번역 중 음역

원본과 다른 알파벳(또는 음소)을 사용하는 언어로 번역하는 경우 음역이 필요할 수 있습니다. 다음 예제에서는 "Hello"를 영어에서 태국어로 번역합니다. 번역을 태국어로 가져오는 것 외에도 라틴 알파벳을 사용하여 번역된 구의 음역을 가져올 수 있습니다.

translate 엔드포인트에서 음역을 가져오려면 toScript 매개 변수를 사용합니다.

참고 항목

사용 가능한 언어 및 음차 옵션의 전체 목록은 언어 지원을 참조하세요.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
   // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    private static readonly string location = "<YOUR-RESOURCE-LOCATION>";

    static async Task Main(string[] args)
    {
        // Output language defined as parameter, with toScript set to latn
        string route = "/translate?api-version=3.0&to=th&toScript=latn";
        string textToTransliterate = "Hello, friend! What did you do today?";
        object[] body = new object[] { new { Text = textToTransliterate } };
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", key);
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);

            // 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();
            Console.WriteLine(result);
        }
    }
}

성공적으로 호출되면 다음과 같은 응답이 표시됩니다. translate 엔드포인트의 응답에는 신뢰도 점수가 있는 감지된 원본 언어, 출력 언어의 알파벳을 사용한 번역 및 라틴 문자를 사용한 음역이 포함됩니다.

[
  {
    "detectedLanguage": {
      "language": "en",
      "score": 1
    },
    "translations": [
      {
        "text": "หวัดดีเพื่อน! วันนี้เธอทำอะไรไปบ้าง ",
        "to": "th",
        "transliteration": {
          "script": "Latn",
          "text": "watdiphuean! wannithoethamaraipaiang"
        }
      }
    ]
  }
]

번역 없이 음역

transliterate 엔드포인트를 사용하여 음역을 가져올 수도 있습니다. 음역 엔드포인트를 사용하는 경우 원본 언어(language), 원본 스크립트/알파벳(fromScript) 및 출력 스크립트/알파벳(toScript)을 매개 변수로 제공해야 합니다. 다음 예제에서는 สวัสดีเพื่อน에 대한 음역을 가져옵니다. วันนี้คุณทำอะไร.

참고 항목

사용 가능한 언어 및 음차 옵션의 전체 목록은 언어 지원을 참조하세요.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
   // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    private static readonly string location = "<YOUR-RESOURCE-LOCATION>";

    static async Task Main(string[] args)
    {
        // For a complete list of options, see API reference.
        // Input and output languages are defined as parameters.
        string route = "/transliterate?api-version=3.0&language=th&fromScript=thai&toScript=latn";
        string textToTransliterate = "สวัสดีเพื่อน! วันนี้คุณทำอะไร";
        object[] body = new object[] { new { Text = textToTransliterate } };
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", key);
            // location required if you're using a multi-service or regional (not global) resource.
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);

            // 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();
            Console.WriteLine(result);
        }
    }
}

성공적으로 호출되면 다음과 같은 응답이 표시됩니다. translate 엔드포인트에 대한 호출과 달리 transliteratetextscript 출력만 반환합니다.

[
   {
      "text":"sawatdiphuean! wannikhunthamarai",

      "script":"latn"
   }
]

문장 길이 가져오기

Translator 서비스를 사용하면 한 문장 또는 일련의 문장에 대한 문자 수를 가져올 수 있습니다. 응답은 감지된 각 문장에 대한 문자 수가 포함된 배열로 반환됩니다. translatebreaksentence 엔드포인트를 사용하여 문장 길이를 가져올 수 있습니다.

번역 중 문장 길이 가져오기

translate 엔드포인트를 사용하여 원본 텍스트 및 번역 출력 모두에 대한 문자 수를 가져올 수 있습니다. 문장 길이(srcSenLentransSenLen)를 반환하려면 includeSentenceLength 매개 변수를 True로 설정해야 합니다.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
   // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    private static readonly string location = "<YOUR-RESOURCE-LOCATION>";

    static async Task Main(string[] args)
    {
        // Include sentence length details.
        string route = "/translate?api-version=3.0&to=es&includeSentenceLength=true";
        string sentencesToCount =
                "Can you tell me how to get to Penn Station? Oh, you aren't sure? That's fine.";
        object[] body = new object[] { new { Text = sentencesToCount } };
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", key);
            // location required if you're using a multi-service or regional (not global) resource.
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);

            // 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();
            Console.WriteLine(result);
        }
    }
}

성공적으로 호출되면 다음과 같은 응답이 표시됩니다. 감지된 소스 언어 및 번역 외에도 원본(srcSentLen) 및 번역(transSentLen) 모두에 대해 감지된 각 문장에 대한 문자 수를 가져옵니다.

[
   {
      "detectedLanguage":{
         "language":"en",
         "score":1.0
      },
      "translations":[
         {
            "text":"¿Puedes decirme cómo llegar a Penn Station? Oh, ¿no estás seguro? Está bien.",
            "to":"es",
            "sentLen":{
               "srcSentLen":[
                  44,
                  21,
                  12
               ],
               "transSentLen":[
                  44,
                  22,
                  10
               ]
            }
         }
      ]
   }
]

번역 없이 문장 길이 가져오기

Translator 서비스를 사용하면 breaksentence 엔드포인트를 사용하여 번역하지 않고 문장 길이를 요청할 수도 있습니다.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
   // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    private static readonly string location = "<YOUR-RESOURCE-LOCATION>";

    static async Task Main(string[] args)
    {
        // Only include sentence length details.
        string route = "/breaksentence?api-version=3.0";
        string sentencesToCount =
                "Can you tell me how to get to Penn Station? Oh, you aren't sure? That's fine.";
        object[] body = new object[] { new { Text = sentencesToCount } };
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", key);
            // location required if you're using a multi-service or regional (not global) resource.
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);

            // 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();
            Console.WriteLine(result);
        }
    }
}

성공적으로 호출되면 다음과 같은 응답이 표시됩니다. translate 엔드포인트에 대한 호출과 달리 breaksentencesentLen이라는 배열의 원본 텍스트에 대한 문자 수만 반환합니다.

[
   {
      "detectedLanguage":{
         "language":"en",
         "score":1.0
      },
      "sentLen":[
         44,
         21,
         12
      ]
   }
]

사전 조회(대체 번역)

엔드포인트를 사용하면 단어 또는 구에 대한 대체 번역을 가져올 수 있습니다. 예를 들어, "sunshine"이라는 단어를 en에서 es로 번역할 때 이 엔드포인트는 ""luz solar," "rayos solares," "soleamiento," "sol," "insolación"을 반환합니다.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
   // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    private static readonly string location = "<YOUR-RESOURCE-LOCATION>";

    static async Task Main(string[] args)
    {
        // See many translation options
        string route = "/dictionary/lookup?api-version=3.0&from=en&to=es";
        string wordToTranslate = "sunlight";
        object[] body = new object[] { new { Text = wordToTranslate } };
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", key);
            // location required if you're using a multi-service or regional (not global) resource.
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);

            // 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();
            Console.WriteLine(result);
        }
    }
}

성공적으로 호출되면 다음과 같은 응답이 표시됩니다. JSON은 이 문서의 다른 몇 가지 예제보다 더 복잡하므로 응답을 더 자세히 살펴보겠습니다. translations 배열에는 번역 목록이 포함됩니다. 이 배열의 각 개체에는 신뢰도 점수(confidence), 최종 사용자 표시에 최적화된 텍스트(displayTarget), 정규화된 텍스트(normalizedText), 음성 부분(posTag), 이전 번역에 대한 정보(backTranslations)가 포함됩니다. 응답에 대한 자세한 내용은 사전 조회를 참조하세요.

[
   {
      "normalizedSource":"sunlight",
      "displaySource":"sunlight",
      "translations":[
         {
            "normalizedTarget":"luz solar",
            "displayTarget":"luz solar",
            "posTag":"NOUN",
            "confidence":0.5313,
            "prefixWord":"",
            "backTranslations":[
               {
                  "normalizedText":"sunlight",
                  "displayText":"sunlight",
                  "numExamples":15,
                  "frequencyCount":702
               },
               {
                  "normalizedText":"sunshine",
                  "displayText":"sunshine",
                  "numExamples":7,
                  "frequencyCount":27
               },
               {
                  "normalizedText":"daylight",
                  "displayText":"daylight",
                  "numExamples":4,
                  "frequencyCount":17
               }
            ]
         },
         {
            "normalizedTarget":"rayos solares",
            "displayTarget":"rayos solares",
            "posTag":"NOUN",
            "confidence":0.1544,
            "prefixWord":"",
            "backTranslations":[
               {
                  "normalizedText":"sunlight",
                  "displayText":"sunlight",
                  "numExamples":4,
                  "frequencyCount":38
               },
               {
                  "normalizedText":"rays",
                  "displayText":"rays",
                  "numExamples":11,
                  "frequencyCount":30
               },
               {
                  "normalizedText":"sunrays",
                  "displayText":"sunrays",
                  "numExamples":0,
                  "frequencyCount":6
               },
               {
                  "normalizedText":"sunbeams",
                  "displayText":"sunbeams",
                  "numExamples":0,
                  "frequencyCount":4
               }
            ]
         },
         {
            "normalizedTarget":"soleamiento",
            "displayTarget":"soleamiento",
            "posTag":"NOUN",
            "confidence":0.1264,
            "prefixWord":"",
            "backTranslations":[
               {
                  "normalizedText":"sunlight",
                  "displayText":"sunlight",
                  "numExamples":0,
                  "frequencyCount":7
               }
            ]
         },
         {
            "normalizedTarget":"sol",
            "displayTarget":"sol",
            "posTag":"NOUN",
            "confidence":0.1239,
            "prefixWord":"",
            "backTranslations":[
               {
                  "normalizedText":"sun",
                  "displayText":"sun",
                  "numExamples":15,
                  "frequencyCount":20387
               },
               {
                  "normalizedText":"sunshine",
                  "displayText":"sunshine",
                  "numExamples":15,
                  "frequencyCount":1439
               },
               {
                  "normalizedText":"sunny",
                  "displayText":"sunny",
                  "numExamples":15,
                  "frequencyCount":265
               },
               {
                  "normalizedText":"sunlight",
                  "displayText":"sunlight",
                  "numExamples":15,
                  "frequencyCount":242
               }
            ]
         },
         {
            "normalizedTarget":"insolación",
            "displayTarget":"insolación",
            "posTag":"NOUN",
            "confidence":0.064,
            "prefixWord":"",
            "backTranslations":[
               {
                  "normalizedText":"heat stroke",
                  "displayText":"heat stroke",
                  "numExamples":3,
                  "frequencyCount":67
               },
               {
                  "normalizedText":"insolation",
                  "displayText":"insolation",
                  "numExamples":1,
                  "frequencyCount":55
               },
               {
                  "normalizedText":"sunstroke",
                  "displayText":"sunstroke",
                  "numExamples":2,
                  "frequencyCount":31
               },
               {
                  "normalizedText":"sunlight",
                  "displayText":"sunlight",
                  "numExamples":0,
                  "frequencyCount":12
               },
               {
                  "normalizedText":"solarization",
                  "displayText":"solarization",
                  "numExamples":0,
                  "frequencyCount":7
               },
               {
                  "normalizedText":"sunning",
                  "displayText":"sunning",
                  "numExamples":1,
                  "frequencyCount":7
               }
            ]
         }
      ]
   }
]

사전 예제(컨텍스트의 번역)

사전 조회를 수행한 후 원본 및 번역 텍스트를 dictionary/examples 엔드포인트에 전달하여 문장 또는 구의 컨텍스트에서 두 용어를 모두 표시하는 예 목록을 가져옵니다. 이전 예제를 기반으로 하여 사전 조회 응답의 normalizedTextnormalizedTarget을 각각 texttranslation으로 사용합니다. 원본 언어(from) 및 출력 대상(to) 매개 변수가 필요합니다.

using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet

class Program
{
    private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
    private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";

    // location, also known as region.
   // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
    private static readonly string location = "<YOUR-RESOURCE-LOCATION>";

    static async Task Main(string[] args)
    {
        // See examples of terms in context
        string route = "/dictionary/examples?api-version=3.0&from=en&to=es";
        object[] body = new object[] { new { Text = "sunlight",  Translation = "luz solar" } } ;
        var requestBody = JsonConvert.SerializeObject(body);

        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            // Build the request.
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(endpoint + route);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", key);
            // location required if you're using a multi-service or regional (not global) resource.
            request.Headers.Add("Ocp-Apim-Subscription-Region", location);

            // 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();
            Console.WriteLine(result);
        }
    }
}

성공적으로 호출되면 다음과 같은 응답이 표시됩니다. 응답에 대한 자세한 내용은 사전 조회를 참조하세요.

[
   {
      "normalizedSource":"sunlight",
      "normalizedTarget":"luz solar",
      "examples":[
         {
            "sourcePrefix":"You use a stake, silver, or ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"Se usa una estaca, plata, o ",
            "targetTerm":"luz solar",
            "targetSuffix":"."
         },
         {
            "sourcePrefix":"A pocket of ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"Una bolsa de ",
            "targetTerm":"luz solar",
            "targetSuffix":"."
         },
         {
            "sourcePrefix":"There must also be ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"También debe haber ",
            "targetTerm":"luz solar",
            "targetSuffix":"."
         },
         {
            "sourcePrefix":"We were living off of current ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"Estábamos viviendo de la ",
            "targetTerm":"luz solar",
            "targetSuffix":" actual."
         },
         {
            "sourcePrefix":"And they don't need unbroken ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"Y ellos no necesitan ",
            "targetTerm":"luz solar",
            "targetSuffix":" ininterrumpida."
         },
         {
            "sourcePrefix":"We have lamps that give the exact equivalent of ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"Disponemos de lámparas que dan el equivalente exacto de ",
            "targetTerm":"luz solar",
            "targetSuffix":"."
         },
         {
            "sourcePrefix":"Plants need water and ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"Las plantas necesitan agua y ",
            "targetTerm":"luz solar",
            "targetSuffix":"."
         },
         {
            "sourcePrefix":"So this requires ",
            "sourceTerm":"sunlight",
            "sourceSuffix":".",
            "targetPrefix":"Así que esto requiere ",
            "targetTerm":"luz solar",
            "targetSuffix":"."
         },
         {
            "sourcePrefix":"And this pocket of ",
            "sourceTerm":"sunlight",
            "sourceSuffix":" freed humans from their ...",
            "targetPrefix":"Y esta bolsa de ",
            "targetTerm":"luz solar",
            "targetSuffix":", liberó a los humanos de ..."
         },
         {
            "sourcePrefix":"Since there is no ",
            "sourceTerm":"sunlight",
            "sourceSuffix":", the air within ...",
            "targetPrefix":"Como no hay ",
            "targetTerm":"luz solar",
            "targetSuffix":", el aire atrapado en ..."
         },
         {
            "sourcePrefix":"The ",
            "sourceTerm":"sunlight",
            "sourceSuffix":" shining through the glass creates a ...",
            "targetPrefix":"La ",
            "targetTerm":"luz solar",
            "targetSuffix":" a través de la vidriera crea una ..."
         },
         {
            "sourcePrefix":"Less ice reflects less ",
            "sourceTerm":"sunlight",
            "sourceSuffix":", and more open ocean ...",
            "targetPrefix":"Menos hielo refleja menos ",
            "targetTerm":"luz solar",
            "targetSuffix":", y más mar abierto ..."
         },
         {
            "sourcePrefix":"",
            "sourceTerm":"Sunlight",
            "sourceSuffix":" is most intense at midday, so ...",
            "targetPrefix":"La ",
            "targetTerm":"luz solar",
            "targetSuffix":" es más intensa al mediodía, por lo que ..."
         },
         {
            "sourcePrefix":"... capture huge amounts of ",
            "sourceTerm":"sunlight",
            "sourceSuffix":", so fueling their growth.",
            "targetPrefix":"... capturan enormes cantidades de ",
            "targetTerm":"luz solar",
            "targetSuffix":" que favorecen su crecimiento."
         },
         {
            "sourcePrefix":"... full height, giving more direct ",
            "sourceTerm":"sunlight",
            "sourceSuffix":" in the winter.",
            "targetPrefix":"... altura completa, dando más ",
            "targetTerm":"luz solar",
            "targetSuffix":" directa durante el invierno."
         }
      ]
   }
]

문제 해결

일반 HTTP 상태 코드

HTTP 상태 코드 설명 가능한 원인
200 OK 요청에 성공했습니다.
400 Bad Request 필수 매개 변수가 없거나 비어 있거나 null입니다. 또는 필수 또는 선택적 매개 변수에 전달된 값이 올바르지 않습니다. 일반적인 문제는 헤더가 너무 긴 경우입니다.
401 Unauthorized 요청에 부여된 권한이 없습니다. 키 또는 토큰이 유효하고 올바른 영역에 있는지 확인하세요. 인증도 참조하세요.
429 요청이 너무 많음 구독에 허용되는 요청의 할당량 또는 속도가 초과되었습니다.
502 잘못된 게이트웨이 네트워크 또는 서버 쪽 문제입니다. 잘못된 헤더를 나타낼 수도 있습니다.

Java 사용자

연결 문제가 발생하는 경우 TLS/SSL 인증서가 만료된 것일 수 있습니다. 이 문제를 해결하려면 프라이빗 저장소에 DigiCertGlobalRootG2.crt를 설치합니다.

다음 단계