异步批量翻译请求将通过 POST 请求提交到翻译器服务终结点。 如果成功,POST 方法将返回
202 Accepted
响应代码,并且服务将创建批处理请求。 经过翻译的文档将会在目标容器中列出。
请确保已将目标文件名指定为目标 URL 的一部分,但 SAS 令牌仍适用于容器。
此示例请求返回了翻译成两种目标语言的单个文档。
"inputs": [
"storageType": "File",
"source": {
"sourceUrl": "{sourceSASUrl}"
"targets": [
"targetUrl": "{targetSASUrl}",
"language": "es"
"targetUrl": "{targetSASUrl}",
"language": "de"
使用自定义词汇表来翻译文档
"inputs": [
"source": {
"sourceUrl": "{sourceSASUrl}"
"targets": [
"targetUrl": "{targetSASUrl}",
"language": "es",
"glossaries": [
"glossaryUrl": "{glossaryUrl/en-es.xlf}",
"format": "xliff"
使用代码来提交文档翻译请求
Node.js
Python
将 Program.cs 替换为 C# 代码示例。
在 Program.cs 中设置终结点、密钥和容器 URL 的值。
若要处理 JSON 数据,请
使用 .NET CLI 添加 Newtonsoft.Json 包
。
从项目目录运行程序。
注意
:Java 源文件(例如
sample.java
)存放在 src/main/
Java
中。
在根目录(例如 sample-project)中使用 Gradle 初始化项目:
gradle init --type basic
当提示你选择一个 DSL 时,选择 Kotlin。
更新 build.gradle.kts
文件。 请记住,你需要根据示例更新 mainClassName
:
plugins {
application
application {
mainClassName = "{NAME OF YOUR CLASS}"
repositories {
mavenCentral()
dependencies {
compile("com.squareup.okhttp:okhttp:2.5.0")
在 java 目录中创建一个 Java 文件,然后复制并粘贴所提供示例中的代码。 请不要忘记添加你的密钥和终结点。
从根目录生成并运行示例:
gradle build
gradle run
对于代码示例,将在指定的位置对共享访问签名 (SAS) URL 进行硬编码。 请记住完成后将 SAS URL 从代码中删除,永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure 托管标识。 有关详细信息,请参阅 Azure 存储安全性。
可能需要根据操作更新以下字段:
static readonly string route = "?api-version={date}";
private static readonly string basePath = "{your-document-translation-endpoint}/translator/document/batches";
private static readonly string key = "{your-api-key}";
static readonly string json = ("{\"inputs\": [{\"source\": {\"sourceUrl\": \"https://YOUR-SOURCE-URL-WITH-READ-LIST-ACCESS-SAS\",\"storageSource\": \"AzureBlob\",\"language\": \"en\"}, \"targets\": [{\"targetUrl\": \"https://YOUR-TARGET-URL-WITH-WRITE-LIST-ACCESS-SAS\",\"storageSource\": \"AzureBlob\",\"category\": \"general\",\"language\": \"es\"}]}]}");
static async Task Main(string[] args)
using HttpClient client = new HttpClient();
using HttpRequestMessage request = new HttpRequestMessage();
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(basePath + route);
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
string result = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
Console.WriteLine($"Status code: {response.StatusCode}");
Console.WriteLine();
Console.WriteLine($"Response Headers:");
Console.WriteLine(response.Headers);
Console.Write("Error");
const axios = require('axios').default;
let basePath = '{your-document-translation-endpoint}/translator/document/batches';
let route = '?api-version={date}';
let key = '{your-api-key}';
let data = JSON.stringify({"inputs": [
"source": {
"sourceUrl": "https://YOUR-SOURCE-URL-WITH-READ-LIST-ACCESS-SAS",
"storageSource": "AzureBlob",
"language": "en"
"targets": [
"targetUrl": "https://YOUR-TARGET-URL-WITH-WRITE-LIST-ACCESS-SAS",
"storageSource": "AzureBlob",
"category": "general",
"language": "es"}]});
let config = {
method: 'post',
baseURL: basePath,
url: route,
headers: {
'Ocp-Apim-Subscription-Key': key,
'Content-Type': 'application/json'
data: data
axios(config)
.then(function (response) {
let result = { statusText: response.statusText, statusCode: response.status, headers: response.headers };
console.log()
console.log(JSON.stringify(result));
.catch(function (error) {
console.log(error);
import requests
base_path = '{your-document-translation-endpoint}/translator/document/batches'
key = '{your-api-key}'
route = '?api-version={date}'
constructed_url = base_path + route
payload= {
"inputs": [
"source": {
"sourceUrl": "https://YOUR-SOURCE-URL-WITH-READ-LIST-ACCESS-SAS",
"storageSource": "AzureBlob",
"language": "en"
"targets": [
"targetUrl": "https://YOUR-TARGET-URL-WITH-WRITE-LIST-ACCESS-SAS",
"storageSource": "AzureBlob",
"category": "general",
"language": "es"
headers = {
'Ocp-Apim-Subscription-Key': key,
'Content-Type': 'application/json'
response = requests.post(constructed_url, headers=headers, json=payload)
print(f'response status code: {response.status_code}\nresponse status: {response.reason}\nresponse headers: {response.headers}')
public class DocumentTranslation {
String key = "{your-api-key}";
String basePath = "{your-document-translation-endpoint}/translator/document/batches";
String route = basePath + "?api-version={date}";
OkHttpClient client = new OkHttpClient();
public void post() throws IOException {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\n \"inputs\": [\n {\n \"source\": {\n \"sourceUrl\": \"https://YOUR-SOURCE-URL-WITH-READ-LIST-ACCESS-SAS\",\n },\n \"language\": \"en\",\n \"storageSource\": \"AzureBlob\"\n },\n \"targets\": [\n {\n \"targetUrl\": \"https://YOUR-TARGET-URL-WITH-WRITE-LIST-ACCESS-SAS\",\n \"category\": \"general\",\n\"language\": \"fr\",\n\"storageSource\": \"AzureBlob\"\n }\n ],\n \"storageType\": \"Folder\"\n }\n ]\n}");
Request request = new Request.Builder()
.url(route).post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
.addHeader("Content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.code());
System.out.println(response.headers());
public static void main(String[] args) {
try {
DocumentTranslation sampleRequest = new DocumentTranslation();
sampleRequest.post();
} catch (Exception e) {
System.out.println(e);
func main() {
basePath := "{your-document-translation-endpoint}/translator/document/batches"
key := "{your-api-key}"
uri := basePath + "?api-version={date}"
method := "POST"
var jsonStr = []byte(`{"inputs":[{"source":{"sourceUrl":"https://YOUR-SOURCE-URL-WITH-READ-LIST-ACCESS-SAS","storageSource":"AzureBlob","language":"en"},"targets":[{"targetUrl":"https://YOUR-TARGET-URL-WITH-WRITE-LIST-ACCESS-SAS","storageSource":"AzureBlob","category":"general","language":"es"}]}]}`)
req, err := http.NewRequest(method, uri, bytes.NewBuffer(jsonStr))
req.Header.Add("Ocp-Apim-Subscription-Key", key)
req.Header.Add("Content-Type", "application/json")
client := &http.Client{}
if err != nil {
fmt.Println(err)
return
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
defer res.Body.Close()
fmt.Println("response status:", res.Status)
fmt.Println("response headers", res.Header)
检索受支持文件格式的列表。 如果成功,此方法将返回 200 OK
响应代码。
Node.js
Python
private static readonly string basePath = "{your-document-translation-endpoint}/translator/document/formats";
static readonly string route = "?api-version={date}&type=document";
private static readonly string key = "{your-api-key}";
static async Task Main(string[] args)
HttpClient client = new HttpClient();
using HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Get;
request.RequestUri = new Uri(basePath + route);
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
HttpResponseMessage response = await client.SendAsync(request);
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine($"Status code: {response.StatusCode}");
Console.WriteLine($"Response Headers: {response.Headers}");
Console.WriteLine();
Console.WriteLine(result);
const axios = require('axios');
let basePath = '{your-document-translation-endpoint}/translator/document/formats}';
let key = '{your-api-key}';
let route = '?api-version={date}&type=document';
let config = {
method: 'get',
url: basePath + route,
headers: {
'Ocp-Apim-Subscription-Key': key
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
.catch(function (error) {
console.log(error);
String key = "{your-api-key}";
String basePath = "{your-document-translation-endpoint}/translator/document/formats";
String url = basePath + "?api-version={date}&type=document";
OkHttpClient client = new OkHttpClient();
public void get() throws IOException {
Request request = new Request.Builder().url(
url).method("GET", null).addHeader("Ocp-Apim-Subscription-Key", key).build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
public static void main(String[] args) throws IOException {
GetJobs jobs = new GetJobs();
jobs.get();
} catch (Exception e) {
System.out.println(e);
import http.client
host = '{your-document-translation-endpoint}/translator/document/formats'
parameters = '?api-version={date}&type=document'
key = '{your-api-key}'
conn = http.client.HTTPSConnection(host)
payload = ''
headers = {
'Ocp-Apim-Subscription-Key': key
conn.request("GET", parameters , payload, headers)
res = conn.getresponse()
data = res.read()
print(res.status)
print()
print(data.decode("utf-8"))
func main() {
basePath := "https://<NAME-OF-YOUR-RESOURCE>.cognitiveservices.azure.com/translator/text/batch/v1.1{your-document-translation-endpoint}/translator/document/formats"
key := "{your-api-key}"
uri := basePath + "?api-version={date}&type=document"
method := "GET"
client := &http.Client {
req, err := http.NewRequest(method, uri, nil)
if err != nil {
fmt.Println(err)
return
req.Header.Add("Ocp-Apim-Subscription-Key", key)
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
fmt.Println(res.StatusCode)
fmt.Println(string(body))
获取翻译作业的状态
在文档翻译请求中获取单个作业的当前状态以及所有作业的摘要。 如果成功,此方法将返回 200 OK
响应代码。
private static readonly string basePath = "{your-document-translation-endpoint}/translator/document/batches/{id}";
static readonly string route = "?api-version={date}";
private static readonly string key = "{your-api-key}";
static async Task Main(string[] args)
HttpClient client = new HttpClient();
using HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Get;
request.RequestUri = new Uri(basePath + route);
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
HttpResponseMessage response = await client.SendAsync(request);
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine($"Status code: {response.StatusCode}");
Console.WriteLine($"Response Headers: {response.Headers}");
Console.WriteLine();
Console.WriteLine(result);
const axios = require('axios');
let basePath = '{your-document-translation-endpoint}/translator/document/batches/{id}';
let key = '{your-api-key}';
let route = '?api-version={date}';
let config = {
method: 'get',
url: endpoint + route,
headers: {
'Ocp-Apim-Subscription-Key': key
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
.catch(function (error) {
console.log(error);
String key = "{your-api-key}";
String basePath = "{your-document-translation-endpoint}/translator/document/batches/{id}";
String url = basePath + "?api-version={date}";
OkHttpClient client = new OkHttpClient();
public void get() throws IOException {
Request request = new Request.Builder().url(
url).method("GET", null).addHeader("Ocp-Apim-Subscription-Key", key).build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
public static void main(String[] args) throws IOException {
GetJobs jobs = new GetJobs();
jobs.get();
} catch (Exception e) {
System.out.println(e);
import http.client
host = '{your-document-translation-endpoint}/translator/document/batches/{id}'
parameters = '?api-version={date}'
key = '{your-api-key}'
conn = http.client.HTTPSConnection(host)
payload = ''
headers = {
'Ocp-Apim-Subscription-Key': key
conn.request("GET", parameters , payload, headers)
res = conn.getresponse()
data = res.read()
print(res.status)
print()
print(data.decode("utf-8"))
func main() {
basePath := "{your-document-translation-endpoint}/translator/document/batches/{id}"
key := "{your-api-key}"
uri := basePath + "?api-version={date}"
method := "GET"
client := &http.Client {
req, err := http.NewRequest(method, uri, nil)
if err != nil {
fmt.Println(err)
return
req.Header.Add("Ocp-Apim-Subscription-Key", key)
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
fmt.Println(res.StatusCode)
fmt.Println(string(body))
获取特定文档的状态
在文档翻译请求中检索某特定文档的状态。 如果成功,此方法将返回 200 OK
响应代码。
Node.js
Python
private static readonly string basePath = "{document-translation-endpoint}/translator/document/batches/{id}/documents/{documentId}";
static readonly string route = "?api-version={date}";
private static readonly string key = "{your-api-key}";
static async Task Main(string[] args)
HttpClient client = new HttpClient();
using HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Get;
request.RequestUri = new Uri(basePath + route);
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
HttpResponseMessage response = await client.SendAsync(request);
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine($"Status code: {response.StatusCode}");
Console.WriteLine($"Response Headers: {response.Headers}");
Console.WriteLine();
Console.WriteLine(result);
const axios = require('axios');
let basePath = '{your-document-translation-endpoint}/translator/document/batches/{id}/documents/{documentId}';
let key = '{your-api-key}';
let route = '?api-version={date}';
let config = {
method: 'get',
url: basePath + route,
headers: {
'Ocp-Apim-Subscription-Key': key
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
.catch(function (error) {
console.log(error);
String key = "{your-api-key}";
String basePath = "{your-document-translation-endpoint}/translator/document/batches/{id}/documents/{documentId}";
String url = endpoint + "?api-version={date}";
OkHttpClient client = new OkHttpClient();
public void get() throws IOException {
Request request = new Request.Builder().url(
url).method("GET", null).addHeader("Ocp-Apim-Subscription-Key", key).build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
public static void main(String[] args) throws IOException {
GetJobs jobs = new GetJobs();
jobs.get();
} catch (Exception e) {
System.out.println(e);
import http.client
host = '{your-document-translation-endpoint}/translator/document/batches/{id}/documents/{documentId}'
parameters = '?api-version={date}'
key = '{your-api-key}'
conn = http.client.HTTPSConnection(host)
payload = ''
headers = {
'Ocp-Apim-Subscription-Key': key
conn.request("GET", parameters , payload, headers)
res = conn.getresponse()
data = res.read()
print(res.status)
print()
print(data.decode("utf-8"))
func main() {
basePath := "{your-document-translation-endpoint}/translator/document/batches/{id}/documents/{documentId}"
key := "{your-api-key}"
uri := basePath + "?api-version={date}"
method := "GET"
client := &http.Client {
req, err := http.NewRequest(method, uri, nil)
if err != nil {
fmt.Println(err)
return
req.Header.Add("Ocp-Apim-Subscription-Key", key)
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
fmt.Println(res.StatusCode)
fmt.Println(string(body))
取消当前正在处理或已排队的作业。 只会取消尚未开始翻译的文档。
Node.js
Python
private static readonly string basePath = "{your-document-translation-endpoint}/translator/document/batches/{id}";
static readonly string route = "?api-version={date}";
private static readonly string key = "{your-api-key}";
static async Task Main(string[] args)
HttpClient client = new HttpClient();
using HttpRequestMessage request = new HttpRequestMessage();
request.Method = HttpMethod.Delete;
request.RequestUri = new Uri(basePath + route);
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
HttpResponseMessage response = await client.SendAsync(request);
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine($"Status code: {response.StatusCode}");
Console.WriteLine($"Response Headers: {response.Headers}");
Console.WriteLine();
Console.WriteLine(result);
const axios = require('axios');
let basePath = '{your-document-translation-endpoint}/translator/document/batches/{id}';
let key = '{your-api-key}';
let route = '?api-version={date}';
let config = {
method: 'delete',
url: basePath + route,
headers: {
'Ocp-Apim-Subscription-Key': key
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
.catch(function (error) {
console.log(error);
String key = "{your-api-key}";
String basePath = "{your-document-translation-endpoint}/translator/document/batches/{id}";
String url = basePath + "?api-version={date}";
OkHttpClient client = new OkHttpClient();
public void get() throws IOException {
Request request = new Request.Builder().url(
url).method("DELETE", null).addHeader("Ocp-Apim-Subscription-Key", key).build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
public static void main(String[] args) throws IOException {
GetJobs jobs = new GetJobs();
jobs.get();
} catch (Exception e) {
System.out.println(e);
import http.client
host = '{your-document-translation-endpoint}/translator/document/batches/{id}'
parameters = '?api-version={date}'
key = '{your-api-key}'
conn = http.client.HTTPSConnection(host)
payload = ''
headers = {
'Ocp-Apim-Subscription-Key': key
conn.request("DELETE", parameters , payload, headers)
res = conn.getresponse()
data = res.read()
print(res.status)
print()
print(data.decode("utf-8"))
func main() {
basePath := "{your-document-translation-endpoint}/translator/document/batches/{id}"
key := "{your-api-key}"
uri := basePath + "?api-version={date}"
method := "DELETE"
client := &http.Client {
req, err := http.NewRequest(method, uri, nil)
if err != nil {
fmt.Println(err)
return
req.Header.Add("Ocp-Apim-Subscription-Key", key)
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
fmt.Println(res.StatusCode)
fmt.Println(string(body))
常见的 HTTP 状态代码
HTTP 状态代码
可能的原因
请求未授权。 检查确保你的密钥或令牌有效并且在正确的区域中。 在 Azure 门户上管理订阅时,请确保使用的是“翻译”单服务资源,而不是“Azure AI 服务”多服务资源。
超出了订阅允许的配额或请求速率。
错误的网关
网络或服务器端问题。 也可能表示标头无效。
了解详细信息
Translator v3 API 参考
使用自定义翻译器创建自定义的语言系统
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:https://aka.ms/ContentUserFeedback。
提交和查看相关反馈