I den här snabbstarten lär du dig att använda tjänsten Translator via REST. Du börjar med grundläggande exempel och går vidare till några grundläggande konfigurationsalternativ som ofta används under utvecklingen, inklusive:
När du har en Azure-prenumeration kan du skapa Translator resurs i Azure Portal för att hämta din nyckel och slutpunkt. När den har distribuerats väljer du Gå till resurs.
Du behöver nyckeln och slutpunkten från resursen för att ansluta ditt program till Translator tjänsten. Du klistrar in nyckeln och slutpunkten i koden nedan senare i snabbstarten. Du hittar dessa värden på sidan Azure Portal nycklar och slutpunkt:
Du kan använda den kostnadsfria prisnivån (F0) för att prova tjänsten och senare uppgradera till en betald nivå för produktion.
När du anropar Translator-tjänsten via REST måste du se till att följande huvuden ingår i varje begäran. Oroa dig inte, vi inkluderar rubrikerna i exempelkoden i följande avsnitt.
Sidhuvuden
Beskrivning
Autentiseringshuvuden
Begärandehuvud som krävs. Ocp-Apim-Subscription-Key
Begärandehuvud krävs om du använder Cognitive Services resurs. Valfritt om du använder Translator resurs.. Ocp-Apim-Subscription-Region
Begärandehuvud som krävs. Anger nyttolastens innehållstyp. Godkänt värde är application/json; charset=UTF-8 .
Innehållslängd
Begärandehuvud som krävs. Längden på begärandetexten.
X-ClientTraceId
Valfritt. Ett klientgenererat GUID som unikt identifierar begäran. Du kan utelämna det här huvudet om du inkluderar spårnings-ID:t i frågesträngen med hjälp av en frågeparameter med namnet ClientTraceId .
Nycklar och slutpunkter
Exemplen på den här sidan använder hårdkodade nycklar och slutpunkter för enkelhetens skull. Kom ihåg att ta bort nyckeln från koden när du är klar och aldrig publicera den offentligt. Överväg att använda ett säkert sätt att lagra och komma åt dina autentiseringsuppgifter för produktion. Mer information Cognitive Services säkerhetsartikeln finns i artikeln om säkerhet.
Översätt text
Kärnåtgärden i Translator är att översätta text. I det här avsnittet skapar du en begäran som tar en enda källa ( from ) och tillhandahåller två utdata ( to ). Sedan granskar vi några parametrar som kan användas för att justera både begäran och svaret.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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=de&to=it";
string textToTranslate = "Hello, world!";
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", subscriptionKey);
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/translate?api-version=3.0"
// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("from", "en")
q.Add("to", "de")
q.Add("to", "it")
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "Hello, world!"},
}
b, _ := json.Marshal(body)
// Build the HTTP POST request
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b))
if err != nil {
log.Fatal(err)
}
// Add required headers to the request
req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// Decode the JSON response
var result interface{}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
log.Fatal(err)
}
// Format and print the response to terminal
prettyJSON, _ := json.MarshalIndent(result, "", " ")
fmt.Printf("%s\n", prettyJSON)
}
Om du vet att du behöver översättning, men inte vet vilket språk texten ska skickas till Translator-tjänsten, kan du använda språkidentifieringsåtgärden. Det finns mer än ett sätt att identifiera källtextspråket. I det här avsnittet lär du dig att använda språkidentifiering med hjälp translate av slutpunkten och detect slutpunkten.
Identifiera källspråk under översättning
Om du inte inkluderar parametern i din översättningsbegäran försöker Translator tjänsten att identifiera from källtextens språk. I svaret får du det identifierade språket ( language ) och ett konfidenspoäng ( score ). Ju närmare score är , innebär att det finns ökad 1.0 konfidens för att identifieringen är korrekt.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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=de&to=it";
string textToTranslate = "Hello, world!";
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", subscriptionKey);
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/translate?api-version=3.0"
// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("to", "de")
q.Add("to", "it")
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "Hello, world!"},
}
b, _ := json.Marshal(body)
// Build the HTTP POST request
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b))
if err != nil {
log.Fatal(err)
}
// Add required headers to the request
req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// Decode the JSON response
var result interface{}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
log.Fatal(err)
}
// Format and print the response to terminal
prettyJSON, _ := json.MarshalIndent(result, "", " ")
fmt.Printf("%s\n", prettyJSON)
}
Det går att använda tjänsten Translator för att identifiera språket i källtexten utan att utföra en översättning. Det gör du med hjälp av /detect slutpunkten.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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 = "Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal.";
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", subscriptionKey);
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/detect?api-version=3.0"
// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal."},
}
b, _ := json.Marshal(body)
// Build the HTTP POST request
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b))
if err != nil {
log.Fatal(err)
}
// Add required headers to the request
req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// Decode the JSON response
var result interface{}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
log.Fatal(err)
}
// Format and print the response to terminal
prettyJSON, _ := json.MarshalIndent(result, "", " ")
fmt.Printf("%s\n", prettyJSON)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
public class Detect {
private static String subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/detect")
.addQueryParameter("api-version", "3.0")
.build();
// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();
// This function performs a POST request.
public String Post() throws IOException {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"[{\"Text\": \"Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal.\"}]");
Request request = new Request.Builder().url(url).post(body)
.addHeader("Ocp-Apim-Subscription-Key", subscriptionKey)
.addHeader("Ocp-Apim-Subscription-Region", location)
.addHeader("Content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
// This function prettifies the json response.
public static String prettify(String json_text) {
JsonParser parser = new JsonParser();
JsonElement json = parser.parse(json_text);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(json);
}
public static void main(String[] args) {
try {
Detect detectRequest = new Detect();
String response = detectRequest.Post();
System.out.println(prettify(response));
} catch (Exception e) {
System.out.println(e);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
var subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/detect',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0'
},
data: [{
'text': 'Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal.'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your subscription key and endpoint
subscription_key = "YOUR_SUBSCRIPTION_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/detect'
constructed_url = endpoint + path
params = {
'api-version': '3.0'
}
constructed_url = endpoint + path
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# You can pass more than one object in body.
body = [{
'text': 'Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal.'
}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))
När du använder slutpunkten innehåller svaret alternativa identifieringar och låter dig veta om översättning och transkribering stöds för alla /detect identifierade språk. Efter ett lyckat anrop bör du se följande svar:
Transkribering är en process för att konvertera ett ord eller en fras från skriptet (alfabetet) för ett språk till ett annat baserat på fonetiska likheter. Du kan till exempel använda transkribering för att konvertera "สวัสดี" ( thai ) till "sawatdi" ( latn ). Det finns mer än ett sätt att utföra transkribering. I det här avsnittet lär du dig att använda språkidentifiering med hjälp translate av slutpunkten och transliterate slutpunkten.
Transkribera under översättning
Om du översätter till ett språk som använder ett annat alfabet (eller fonem) än din källa kan du behöva en transkribering. I det här exemplet översätter vi "Hello" från engelska till thailändska. Förutom att få översättningen på thailändska får du en transkribering av den översatta frasen med hjälp av det latinska alfabetet.
Om du vill hämta en transkribering translate från slutpunkten använder du toScript parametern .
Anteckning
En fullständig lista över tillgängliga språk och transkriberingsalternativ finns i språkstöd.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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";
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", subscriptionKey);
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/translate?api-version=3.0"
// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("to", "th")
q.Add("toScript", "latn")
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "Hello"},
}
b, _ := json.Marshal(body)
// Build the HTTP POST request
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b))
if err != nil {
log.Fatal(err)
}
// Add required headers to the request
req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// Decode the JSON response
var result interface{}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
log.Fatal(err)
}
// Format and print the response to terminal
prettyJSON, _ := json.MarshalIndent(result, "", " ")
fmt.Printf("%s\n", prettyJSON)
}
Efter ett lyckat anrop bör du se följande svar. Tänk på att svaret från slutpunkten innehåller det identifierade källspråket med en konfidenspoäng, en översättning med utdataspråkets alfabet och en transkribering med hjälp av det translate latinska alfabetet.
Du kan också använda transliterate slutpunkten för att hämta en transkribering. När du använder transkriberingsslutpunkten måste du ange källspråket ( ), källskriptet/alfabetet ( ) och language utdataskriptet/alfabetet fromScript ( ) som toScript parametrar. I det här exemplet ska vi hämta transkribering för สวัสดี.
Anteckning
En fullständig lista över tillgängliga språk och transkriberingsalternativ finns i språkstöd.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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 = "/translate?api-version=3.0&to=th&toScript=latn";
string textToTransliterate = "Hello";
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", subscriptionKey);
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/transliterate?api-version=3.0"
// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("language", "th")
q.Add("fromScript", "thai")
q.Add("toScript", "latn")
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "สวัสดี"},
}
b, _ := json.Marshal(body)
// Build the HTTP POST request
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b))
if err != nil {
log.Fatal(err)
}
// Add required headers to the request
req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// Decode the JSON response
var result interface{}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
log.Fatal(err)
}
// Format and print the response to terminal
prettyJSON, _ := json.MarshalIndent(result, "", " ")
fmt.Printf("%s\n", prettyJSON)
}
Efter ett lyckat anrop bör du se följande svar. Till skillnad från -anropet translate till transliterate slutpunkten returnerar endast script - och -utdata text .
[
{
"script": "latn",
"text": "sawatdi"
}
]
Hämta meningslängd
Med Translator tjänsten kan du hämta antalet tecken för en mening eller en serie meningar. Svaret returneras som en matris, där teckenantal har identifierats för varje mening. Du kan hämta meningslängder med translatebreaksentence slutpunkterna och .
Hämta meningslängd under översättning
Du kan hämta teckenantal för både källtext och översättningsutdata med hjälp av translate slutpunkten. Om du vill returnera srcSenLen meningslängden transSenLen ( och ) måste du ange includeSentenceLength parametern till True .
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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", subscriptionKey);
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/translate?api-version=3.0"
// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("to", "es")
q.Add("includeSentenceLength", "true")
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "Can you tell me how to get to Penn Station? Oh, you aren't sure? That's fine."},
}
b, _ := json.Marshal(body)
// Build the HTTP POST request
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b))
if err != nil {
log.Fatal(err)
}
// Add required headers to the request
req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// Decode the JSON response
var result interface{}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
log.Fatal(err)
}
// Format and print the response to terminal
prettyJSON, _ := json.MarshalIndent(result, "", " ")
fmt.Printf("%s\n", prettyJSON)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
public class Translate {
private static String subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/translate")
.addQueryParameter("api-version", "3.0")
.addQueryParameter("to", "es")
.addQueryParameter("includeSentenceLength", "true")
.build();
// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();
// This function performs a POST request.
public String Post() throws IOException {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"[{\"Text\": \"Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.\"}]");
Request request = new Request.Builder().url(url).post(body)
.addHeader("Ocp-Apim-Subscription-Key", subscriptionKey)
.addHeader("Ocp-Apim-Subscription-Region", location)
.addHeader("Content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
// This function prettifies the json response.
public static String prettify(String json_text) {
JsonParser parser = new JsonParser();
JsonElement json = parser.parse(json_text);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(json);
}
public static void main(String[] args) {
try {
Translate translateRequest = new Translate();
String response = translateRequest.Post();
System.out.println(prettify(response));
} catch (Exception e) {
System.out.println(e);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
var subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/translate',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0',
'to': 'es',
'includeSentenceLength': true
},
data: [{
'text': 'Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your subscription key and endpoint
subscription_key = "YOUR_SUBSCRIPTION_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/translate'
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'to': 'es',
'includeSentenceLength': True
}
constructed_url = endpoint + path
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# You can pass more than one object in body.
body = [{
'text': 'Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.'
}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))
Efter ett lyckat anrop bör du se följande svar. Förutom det identifierade källspråket och översättningen får du teckenantal för varje identifierade mening för både källan ( srcSentLen ) och översättningen ( transSentLen ).
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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", subscriptionKey);
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/breaksentence?api-version=3.0"
// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "Can you tell me how to get to Penn Station? Oh, you aren't sure? That's fine."},
}
b, _ := json.Marshal(body)
// Build the HTTP POST request
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b))
if err != nil {
log.Fatal(err)
}
// Add required headers to the request
req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// Decode the JSON response
var result interface{}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
log.Fatal(err)
}
// Format and print the response to terminal
prettyJSON, _ := json.MarshalIndent(result, "", " ")
fmt.Printf("%s\n", prettyJSON)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
public class BreakSentence {
private static String subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/breaksentence")
.addQueryParameter("api-version", "3.0")
.build();
// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();
// This function performs a POST request.
public String Post() throws IOException {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"[{\"Text\": \"Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.\"}]");
Request request = new Request.Builder().url(url).post(body)
.addHeader("Ocp-Apim-Subscription-Key", subscriptionKey)
.addHeader("Ocp-Apim-Subscription-Region", location)
.addHeader("Content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
// This function prettifies the json response.
public static String prettify(String json_text) {
JsonParser parser = new JsonParser();
JsonElement json = parser.parse(json_text);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(json);
}
public static void main(String[] args) {
try {
BreakSentence breakSentenceRequest = new BreakSentence();
String response = breakSentenceRequest.Post();
System.out.println(prettify(response));
} catch (Exception e) {
System.out.println(e);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
var subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/breaksentence',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0'
},
data: [{
'text': 'Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your subscription key and endpoint
subscription_key = "YOUR_SUBSCRIPTION_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/breaksentence'
constructed_url = endpoint + path
params = {
'api-version': '3.0'
}
constructed_url = endpoint + path
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# You can pass more than one object in body.
body = [{
'text': 'Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.'
}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, indent=4, separators=(',', ': ')))
Efter ett lyckat anrop bör du se följande svar. Till skillnad från translate anropet till breaksentence slutpunkten returnerar endast antalet tecken för källtexten i en matris med namnet sentLen .
Med slutpunkten kan du få alternativa översättningar för ett ord eller en fras. När du till exempel översätter ordet "" från till returnerar den här slutpunkten både enes "tiburón" och "escuescu".
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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 = "shark";
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", subscriptionKey);
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/dictionary/lookup?api-version=3.0"
// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("from", "en")
q.Add("to", "es")
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "shark"},
}
b, _ := json.Marshal(body)
// Build the HTTP POST request
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b))
if err != nil {
log.Fatal(err)
}
// Add required headers to the request
req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// Decode the JSON response
var result interface{}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
log.Fatal(err)
}
// Format and print the response to terminal
prettyJSON, _ := json.MarshalIndent(result, "", " ")
fmt.Printf("%s\n", prettyJSON)
}
Efter ett lyckat anrop bör du se följande svar. Låt oss dela upp detta eftersom JSON är mer komplext än några av de andra exemplen i den här artikeln. Matrisen translations innehåller en lista över översättningar. Varje objekt i den här matrisen innehåller en konfidenspoäng ( ), den text som är optimerad för slutanvändarvisning confidence ( ), den normaliserade texten ( ), delen av tal ( ) och displayTarget information om föregående översättning ( normalizedTextposTagbackTranslations ). Mer information om svaret finns i Ordlisteuppslag
När du har utfört en ordlisteuppslag kan du skicka källtexten och översättningen till slutpunkten för att hämta en lista med exempel som visar båda termerna i kontexten för en mening dictionary/examples eller fras. Utifrån föregående exempel använder du och från normalizedTextnormalizedTarget ordlistesvaret för sökning som texttranslation respektive. Parametrarna källspråk ( from ) och utdatamål ( to ) krävs.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
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 = "Shark", Translation = "tiburón" } } ;
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", subscriptionKey);
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);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
subscriptionKey := "YOUR-SUBSCRIPTION-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/dictionary/examples?api-version=3.0"
// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("from", "en")
q.Add("to", "es")
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
Translation string
}{
{
Text: "Shark",
Translation: "tiburón",
},
}
b, _ := json.Marshal(body)
// Build the HTTP POST request
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b))
if err != nil {
log.Fatal(err)
}
// Add required headers to the request
req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator Text API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// Decode the JSON response
var result interface{}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
log.Fatal(err)
}
// Format and print the response to terminal
prettyJSON, _ := json.MarshalIndent(result, "", " ")
fmt.Printf("%s\n", prettyJSON)
}
Efter ett lyckat anrop bör du se följande svar. Mer information om svaret finns i Ordlisteuppslag
[
{
"examples": [
{
"sourcePrefix": "More than a match for any ",
"sourceSuffix": ".",
"sourceTerm": "shark",
"targetPrefix": "Más que un fósforo para cualquier ",
"targetSuffix": ".",
"targetTerm": "tiburón"
},
{
"sourcePrefix": "Same with the mega ",
"sourceSuffix": ", of course.",
"sourceTerm": "shark",
"targetPrefix": "Y con el mega ",
"targetSuffix": ", por supuesto.",
"targetTerm": "tiburón"
},
{
"sourcePrefix": "A ",
"sourceSuffix": " ate it.",
"sourceTerm": "shark",
"targetPrefix": "Te la ha comido un ",
"targetSuffix": ".",
"targetTerm": "tiburón"
}
],
"normalizedSource": "shark",
"normalizedTarget": "tiburón"
}
]
Felsökning
Vanliga HTTP-statuskoder
HTTP-statuskod
Beskrivning
Möjlig orsak
200
OK
Begäran lyckades.
400
Felaktig begäran
En obligatorisk parameter saknas, är tom eller null. Eller så är värdet som skickas till antingen en obligatorisk eller valfri parameter ogiltig. Ett vanligt problem är en rubrik som är för lång.
401
Behörighet saknas
Begäran har inte auktoriserats. Kontrollera att din prenumerationsnyckel eller token är giltig och i rätt region. Se ävenAutentisering.
429
För många begäranden
Du har överskridit kvoten eller frekvensen för begäranden som tillåts för din prenumeration.
502
Felaktig gateway
Problem på nätverks- eller serversidan. Kan också tyda på ogiltiga huvuden.
Java-användare
Om du får anslutningsproblem kan det vara så att SSL-certifikatet har upphört att gälla. Lös problemet genom att installera DigiCertGlobalRootG2.crt i ditt privata arkiv.