您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:使用 Java 通过文本翻译 API 来翻译字符串Quickstart: Use the Translator Text API to translate a string using Java

本快速入门介绍如何使用 Java 和文本翻译 REST API 将文本字符串从英文翻译为意大利文和德文。In this quickstart, you'll learn how to translate a text string from English to Italian and German using Java and the Translator Text REST API.

此快速入门需要包含文本翻译资源的 Azure 认知服务帐户This quickstart requires an Azure Cognitive Services account with a Translator Text resource. 如果没有帐户,可以使用免费试用版获取订阅密钥。If you don't have an account, you can use the free trial to get a subscription key.

先决条件Prerequisites

使用 Gradle 初始化项目Initialize a project with Gradle

首先,创建此项目的工作目录。Let's start by creating a working directory for this project. 从命令行(或终端)中,运行以下命令:From the command line (or terminal), run this command:

mkdir translator-sample
cd translator-sample

接下来,初始化一个 Gradle 项目。Next, you're going to initialize a Gradle project. 此命令将创建 Gradle 的基本生成文件,最重要的是 build.gradle.kts,它在运行时用来创建并配置应用程序。This command will create essential build files for Gradle, most importantly, the build.gradle.kts, which is used at runtime to create and configure your application. 从工作目录运行以下命令:Run this command from your working directory:

gradle init --type basic

当提示你选择一个 DSL 时,选择 KotlinWhen prompted to choose a DSL, select Kotlin.

配置生成文件Configure the build file

找到 build.gradle.kts 并使用你喜欢使用的 IDE 或文本编辑器将其打开。Locate build.gradle.kts and open it with your favorite IDE or text editor. 然后将以下生成配置复制到其中:Then copy in this build configuration:

plugins {
    java
    application
}
application {
    mainClassName = "Translate"
}
repositories {
    mavenCentral()
}
dependencies {
    compile("com.squareup.okhttp:okhttp:2.5.0")
    compile("com.google.code.gson:gson:2.8.5")
}

请注意,此示例依赖于 HTTP 请求的 OkHttp 以及 Gson 来处理和分析 JSON。Take note that this sample has dependencies on OkHttp for HTTP requests, and Gson to handle and parse JSON. 如果要详细了解生成配置,请参阅创建新的 Gradle 生成If you'd like to learn more about build configurations, see Creating New Gradle Builds.

创建 Java 文件Create a Java file

为示例应用创建一个文件夹。Let's create a folder for your sample app. 从工作目录中,运行:From your working directory, run:

mkdir -p src/main/java

接下来,在此文件夹中,创建一个名为 Translate.java 的文件。Next, in this folder, create a file named Translate.java.

导入所需的库Import required libraries

打开 Translate.java 并添加以下 import 语句:Open Translate.java and add these import statements:

import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;

定义变量Define variables

首先,为你的项目创建一个公共类:First, you'll need to create a public class for your project:

public class Translate {
  // All project code goes here...
}

将以下行添加到 Translate 类。Add these lines to the Translate class. 你会注意到,除了 api-version,还有两个参数已追加到 urlYou'll notice that along with the api-version, two additional parameters have been appended to the url. 这些参数用于设置翻译输出。These parameters are used to set the translation outputs. 在此示例中,它设置为德语 (de) 和意大利语 (it)。In this sample, it's set to German (de) and Italian (it). 确保更新订阅密钥值。Make sure you update the subscription key value.

String subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
String url = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=de,it";

创建客户端并生成请求Create a client and build a request

将以下行添加到 Translate 类来实例化 OkHttpClientAdd this line to the Translate class to instantiate the OkHttpClient:

// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();

接下来,我们将生成 POST 请求。Next, let's build the POST request. 可随意更改用于翻译的文本。Feel free to change the text for translation. 文本必须进行转义。The text must be escaped.

// This function performs a POST request.
public String Post() throws IOException {
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType,
            "[{\n\t\"Text\": \"Welcome to Microsoft Translator. Guess how many languages I speak!\"\n}]");
    Request request = new Request.Builder()
            .url(url).post(body)
            .addHeader("Ocp-Apim-Subscription-Key", subscriptionKey)
            .addHeader("Content-type", "application/json").build();
    Response response = client.newCall(request).execute();
    return response.body().string();
}

创建一个函数来分析响应Create a function to parse the response

这个简单的函数分析来自文本翻译服务的 JSON 响应并对其进行美化。This simple function parses and prettifies the JSON response from the Translator Text service.

// 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);
}

将其放在一起Put it all together

最后一步是发出请求并获得响应。The last step is to make a request and get a response. 将以下行添加你的项目:Add these lines to your project:

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);
    }
}

运行示例应用Run the sample app

上述操作完成后,就可以运行示例应用了。That's it, you're ready to run your sample app. 从命令行(或终端会话)导航到工作目录的根,然后运行以下命令:From the command line (or terminal session), navigate to the root of your working directory and run:

gradle build

当生成完成后,请运行:When the build completes, run:

gradle run

示例响应Sample response

[
  {
    "detectedLanguage": {
      "language": "en",
      "score": 1.0
    },
    "translations": [
      {
        "text": "Willkommen bei Microsoft Translator. Erraten Sie, wie viele Sprachen ich spreche!",
        "to": "de"
      },
      {
        "text": "Benvenuti a Microsoft Translator. Indovinate quante lingue parlo!",
        "to": "it"
      }
    ]
  }
]

后续步骤Next steps

浏览此快速入门的示例代码和其他内容,包括音译和语言识别,以及 GitHub 上的其他示例文本翻译项目。Explore the sample code for this quickstart and others, including transliteration and language identification, as well as other sample Translator Text projects on GitHub.

另请参阅See also