In my last post, I have mentioned about Google
Translation API and how to invoke the api using GCP Platform console and via
Postman using API Keys. Now, we will see how to use in our Java code by using Service
account keys. To use Service Account Keys, we need to install the client
library. Following dependency need to add to the pom.xml file of our project,
In GCP Console when we create a service account key, a JSON file
which contains the service account key will be downloaded to our computer. The
next step is to add the environment variable GOOGLE_APPLICATION_CREDENTIALS to
the file path of the JSON file that contains your service account key as below,
Here is a sample code to test the translation,
import
com.google.cloud.translate.Translate;
import
com.google.cloud.translate.Translate.TranslateOption;
import
com.google.cloud.translate.TranslateOptions;
import
com.google.cloud.translate.Translation;
public
class TranslationApi {
public static void main(String...
args) throws Exception {
// Instantiates a client
Translate translate =
TranslateOptions.getDefaultInstance()
.getService();
String text =
"Hello";
// Translates some text
into Chinese (Traditional)
Translation translation
= translate.translate(text,
TranslateOption.sourceLanguage("en"),
TranslateOption.targetLanguage("zh-TW"));
System.out.println("Word
in English - " + text);
System.out.println("Word
in Chinese (Traditional) - "
+
translation.getTranslatedText());
}
}
The Console Output will be,
Word in English - Hello
Word in Chinese (Traditional) - ??
In Eclipse console, chinese characters are
displayed as “??..” by default. To display the chinese characters, we need to
change the run configuration as follows,
After the above change, the console output will
be,
Word in English - Hello
Word in Chinese (Traditional) - 你好







