快速入门:Azure AI 翻译 REST API

试用最新版本的 Azure AI 翻译。 在本快速入门中,开始使用翻译器服务以所选的编程语言或 REST API 翻译文本。 对于此项目,建议你在学习技术时使用免费定价层 (F0),在以后再升级到付费层进行生产。

先决条件

需要一个活动 Azure 订阅。 如果没有 Azure 订阅,可创建一个试用版订阅

  • 获得 Azure 订阅后,在 Azure 门户中创建一个翻译器资源

  • 部署资源后,选择“转到资源”并检索密钥和终结点。

    • 需要从资源获取密钥和终结点,以便将应用程序连接到翻译器服务。 稍后需要在本快速入门中将密钥和终结点粘贴到代码中。 可以在 Azure 门户的“密钥和终结点”页面上找到这些值:

      屏幕截图:Azure 门户的“密钥和终结点”页面。

      备注

      • 对于本快速入门,建议使用文本翻译单服务全局资源。
      • 使用单服务全局资源,你将在 REST API 请求中包含一个授权标头 (Ocp-Apim-Subscription-key)。 Ocp-Apim-Subscription-key 的值是文本翻译订阅的 Azure 密钥。
      • 如果选择使用 Azure AI 多服务或区域翻译资源,则需要两个身份验证标头(Ocp-Api-Subscription-KeyOcp-Api-Subscription-Region)。 Ocp-Apim-Subscription-Region 的值是与订阅关联的区域。
      • 有关如何使用 Ocp-Apim-Subscription-Region 标头的详细信息,请参阅文本翻译 REST API 标头

标头

若要通过 REST API 调用翻译器服务,需要在每个请求中包含以下标头。 不用担心,我们会在每种编程语言的示例代码中为你包含标头。

有关翻译器身份验证选项的详细信息,请参阅翻译器 v3 参考指南。

标头 条件
Ocp-Apim-Subscription-Key Azure 门户中的翻译器服务密钥。 必需
Ocp-Apim-Subscription-Region 创建资源的区域。 • 使用 Azure AI 多服务或区域(地理)资源(如“中国北部”)时为必填项
• 使用单服务全局翻译资源时为可选项
Content-Type 有效负载的内容类型。 接受的值为 application/jsoncharset=UTF-8 必需
Content-Length 请求正文的长度 可选

重要

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅 Azure AI 服务安全性一文。

翻译文本

翻译器服务的核心操作是翻译文本。 在本快速入门中,你使用所选的编程语言生成一个请求,该请求采用单个源 (from) 并提供两个输出 (to)。 然后,我们将查看一些参数,这些参数可用于调整请求和响应。

有关 Azure AI 翻译服务请求限制的详细信息,请参阅文本翻译请求限制

设置 Java 环境

  • 应使用最新版本的 Visual Studio Code 或者你首选的 IDE。 请参阅 Visual Studio Code 中的 Java

    提示

    • Visual Studio Code 提供适用于 Windows 和 macOS 的 "Java 编码包"。该编码包是 VS Code、Java 开发工具包 (JDK) 和 Microsoft 建议扩展的集合。 编码包还可用于修复现有开发环境。
    • 如果使用 VS Code 和适用于 Java 的编码包,请安装 Gradle for Java 扩展。
  • 如果不使用 Visual Studio Code,请确保在开发环境中安装了以下内容:

创建新的 Gradle 项目

  1. 在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建名为“translator-text-app”的新目录,并导航到该目录。

    mkdir translator-text-app && translator-text-app
    
     mkdir translator-text-app; cd translator-text-app
    
  2. 从 translator-text-app 目录运行 gradle init 命令。 此命令将创建 Gradle 的基本生成文件,其中包括 build.gradle.kts - 在运行时将使用该文件创建并配置应用程序。

    gradle init --type basic
    
  3. 当提示你选择一个 DSL 时,选择 Kotlin

  4. ReturnEnter 接受默认项目名称 (translator-text-app)。

  5. 使用以下代码更新 build.gradle.kts

plugins {
  java
  application
}
application {
  mainClass.set("TranslatorText")
}
repositories {
  mavenCentral()
}
dependencies {
  implementation("com.squareup.okhttp3:okhttp:4.10.0")
  implementation("com.google.code.gson:gson:2.9.0")
}

创建 Java 应用程序

  1. 从 translator-text-app 目录运行以下命令:

    mkdir -p src/main/java
    

    创建以下目录结构:

    屏幕截图:Java 目录结构。

  2. 导航到 java 目录,创建一个名为 TranslatorText.java 的文件。

    提示

    • 可以使用 Powershell 创建新文件。

    • 按住 Shift 键并右键单击该文件夹,在项目目录中打开 Powershell 窗口。

    • 输入以下命令:New-Item TranslatorText.java

    • 还可以在 IDE 中创建名为 TranslatorText.java 的新文件并将其保存到 java 目录。

  3. 在 IDE 中打开 TranslatorText.java 文件,然后将以下代码示例复制并粘贴到应用程序中。 确保将密钥更新为 Azure 门户翻译器实例中的某个密钥值:

import java.io.IOException;

import com.google.gson.*;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TranslatorText {
    private static String key = "<your-translator-key";

    // 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 String location = "<YOUR-RESOURCE-LOCATION>";


    // 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\": \"I would really like to drive your car around the block a few times!\"}]");
        Request request = new Request.Builder()
                .url("https://api.translator.azure.cn/translate?api-version=3.0&from=en&to=fr&to=zu")
                .post(body)
                .addHeader("Ocp-Apim-Subscription-Key", key)
                // location required if you're using a multi-service or regional (not global) resource.
                .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 {
            TranslatorText translateRequest = new TranslatorText();
            String response = translateRequest.Post();
            System.out.println(prettify(response));
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

生成和运行 Java 试应用程序

将代码示例添加到应用程序后,导航回到主项目目录 translator-text-app,打开控制台窗口,然后输入以下命令

  1. 使用 build 命令生成应用程序:

    gradle build
    
  2. 使用 run 命令运行应用程序:

    gradle run
    

翻译输出:

成功调用后,应会看到以下响应:

[
  {
    "translations": [
      {
        "text": "J'aimerais vraiment conduire votre voiture autour du pâté de maisons plusieurs fois!",
        "to": "fr"
      },
      {
        "text": "Ngingathanda ngempela ukushayela imoto yakho endaweni evimbelayo izikhathi ezimbalwa!",
        "to": "zu"
      }
    ]
  }
]

后续步骤

完成了,恭喜! 你已了解如何使用翻译器服务翻译文本。

请浏览我们的操作指南文档并深入了解翻译服务的功能: