Quickstart: Use the Translator Text API to detect text language using Java

In this quickstart, you'll learn how to detect the language of provided text using Java and the Translator Text REST API.

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.


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 detect-sample
cd detect-sample

Next, you're going to initialize a Gradle project. 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

When prompted to choose a DSL, select Kotlin.

Configure the build file

Locate build.gradle.kts and open it with your favorite IDE or text editor. Then copy in this build configuration:

plugins {
application {
    mainClassName = "Detect"
repositories {
dependencies {

Take note that this sample has dependencies on OkHttp for HTTP requests, and Gson to handle and parse JSON. If you'd like to learn more about build configurations, see Creating New Gradle Builds.

Create a Java file

Let's create a folder for your sample app. From your working directory, run:

mkdir -p src/main/java

Next, in this folder, create a file named Detect.java.

Import required libraries

Open Detect.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 Detect {
  // All project code goes here...

Add these lines to the Detect class:

String subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
String url = "https://api.cognitive.microsofttranslator.com/detect?api-version=3.0";

If you are using a Cognitive Services multi-service subscription, you must also include the Ocp-Apim-Subscription-Region in your request parameters. Learn more about authenticating with the multi-service subscription.

Create a client and build a request

Add this line to the Detect class to instantiate the OkHttpClient:

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

Next, let's build the POST request. Feel free to change the text for language detection.

// 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\": \"Salve mondo!\"\n}]");
    Request request = new Request.Builder()
            .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

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 {
        Detect detectRequest = new Detect();
        String response = detectRequest.Post();
    } catch (Exception 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

Find the country/region abbreviation in this list of languages.

    "language": "it",
    "score": 1.0,
    "isTranslationSupported": true,
    "isTransliterationSupported": false,
    "alternatives": [
        "language": "pt",
        "score": 1.0,
        "isTranslationSupported": true,
        "isTransliterationSupported": false
        "language": "en",
        "score": 1.0,
        "isTranslationSupported": true,
        "isTransliterationSupported": false

Next steps

Explore the sample code for this quickstart and others, including translation and transliteration, as well as other sample Translator Text projects on GitHub.

See also