Tuesday, 17 April 2018

How to use Google Translate API in Java application ?

You can do the language translation using Google Translate API. Below is the Java code for integration.

import java.util.Arrays;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.translate.Translate;
import com.google.api.services.translate.model.TranslationsListResponse;
import com.google.api.services.translate.model.TranslationsResource;

public class GoogleTranslationAPISample {
public static void main(String[] arguments) throws GeneralSecurityException, IOException 
    {
        Translate t = new Translate.Builder(
                GoogleNetHttpTransport.newTrustedTransport()
                , GsonFactory.getDefaultInstance(), null)
// Set your application name
                .setApplicationName("sample-Example")
                .build();
        Translate.Translations.List list = t.new Translations().list(
                Arrays.asList(
// Pass in list of strings to be translated
                "Hello World",
                "How to use Google Translate from Java"),
// Target language
                "es"); // es for spanish

// TODO: Set your API-Key from https://console.developers.google.com/
// list.setKey("your-api-key");
        
//list.setKey("AIdwaSyCAKK7htoeT8i8ArmITELoDMyuiorooe5wk-cKs5g"); // my test credentials

        TranslationsListResponse response = list.execute();
        for (TranslationsResource translationsResource : response.getTranslations())
        {
            System.out.println(translationsResource.getTranslatedText());
        }
    }
}

Maven Dependencies :

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-translate</artifactId>
  <version>1.24.1</version>
</dependency>
<dependency>

  <groupId>com.google.api-client</groupId>
  <artifactId>google-api-client-gson</artifactId>
  <version>1.23.0</version>
</dependency>

References :
https://cloud.google.com/vision/docs/libraries
https://github.com/GoogleCloudPlatform/java-docs-samples