How to use Google Translate API in my Java application?

123,230

Solution 1

You can use google script which has FREE translate API. All you need is a common google account and do these THREE EASY STEPS.
1) Create new script with such code on google script:

var mock = {
  parameter:{
    q:'hello',
    source:'en',
    target:'fr'
  }
};


function doGet(e) {
  e = e || mock;

  var sourceText = ''
  if (e.parameter.q){
    sourceText = e.parameter.q;
  }

  var sourceLang = '';
  if (e.parameter.source){
    sourceLang = e.parameter.source;
  }

  var targetLang = 'en';
  if (e.parameter.target){
    targetLang = e.parameter.target;
  }

  var translatedText = LanguageApp.translate(sourceText, sourceLang, targetLang, {contentType: 'html'});

  return ContentService.createTextOutput(translatedText).setMimeType(ContentService.MimeType.JSON);
}

2) Click Publish -> Deploy as webapp -> Who has access to the app: Anyone even anonymous -> Deploy. And then copy your web app url, you will need it for calling translate API.
google script deploy

3) Use this java code for testing your API:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Translator {

    public static void main(String[] args) throws IOException {
        String text = "Hello world!";
        //Translated text: Hallo Welt!
        System.out.println("Translated text: " + translate("en", "de", text));
    }

    private static String translate(String langFrom, String langTo, String text) throws IOException {
        // INSERT YOU URL HERE
        String urlStr = "https://your.google.script.url" +
                "?q=" + URLEncoder.encode(text, "UTF-8") +
                "&target=" + langTo +
                "&source=" + langFrom;
        URL url = new URL(urlStr);
        StringBuilder response = new StringBuilder();
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();
    }

}

As it is free, there are QUATA LIMITS: https://docs.google.com/macros/dashboard

Solution 2

Use java-google-translate-text-to-speech instead of Google Translate API v2 Java.

About java-google-translate-text-to-speech

Api unofficial with the main features of Google Translate in Java.

Easy to use!

It also provide text to speech api. If you want to translate the text "Hello!" in Romanian just write:

Translator translate = Translator.getInstance();
String text = translate.translate("Hello!", Language.ENGLISH, Language.ROMANIAN);
System.out.println(text); // "Bună ziua!" 

It's free!

As @r0ast3d correctly said:

Important: Google Translate API v2 is now available as a paid service. The courtesy limit for existing Translate API v2 projects created prior to August 24, 2011 will be reduced to zero on December 1, 2011. In addition, the number of requests your application can make per day will be limited.

This is correct: just see the official page:

Google Translate API is available as a paid service. See the Pricing and FAQ pages for details.

BUT, java-google-translate-text-to-speech is FREE!

Example!

I've created a sample application that demonstrates that this works. Try it here: https://github.com/IonicaBizau/text-to-speech

Solution 3

Generate your own API key here. Check out the documentation here.

You may need to set up a billing account when you try to enable the Google Cloud Translation API in your account.

Below is a quick start example which translates two English strings to Spanish:

import java.io.IOException;
import java.security.GeneralSecurityException;
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 QuickstartSample
{
    public static void main(String[] arguments) throws IOException, GeneralSecurityException
    {
        Translate t = new Translate.Builder(
                GoogleNetHttpTransport.newTrustedTransport()
                , GsonFactory.getDefaultInstance(), null)
                // Set your application name
                .setApplicationName("Stackoverflow-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");

        // TODO: Set your API-Key from https://console.developers.google.com/
        list.setKey("your-api-key");
        TranslationsListResponse response = list.execute();
        for (TranslationsResource translationsResource : response.getTranslations())
        {
            System.out.println(translationsResource.getTranslatedText());
        }
    }
}

Required maven dependencies for the code snippet:

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

<dependency>
    <groupId>com.google.http-client</groupId>
    <artifactId>google-http-client-gson</artifactId>
    <version>LATEST</version>
</dependency>

Solution 4

I’m tired of looking for free translators and the best option for me was Selenium (more precisely selenide and webdrivermanager) and https://translate.google.com

import io.github.bonigarcia.wdm.ChromeDriverManager;
import com.codeborne.selenide.Configuration;
import io.github.bonigarcia.wdm.DriverManagerType;
import static com.codeborne.selenide.Selenide.*;

public class Main {

    public static void main(String[] args) throws IOException, ParseException {

        ChromeDriverManager.getInstance(DriverManagerType.CHROME).version("76.0.3809.126").setup();
        Configuration.startMaximized = true;
        open("https://translate.google.com/?hl=ru#view=home&op=translate&sl=en&tl=ru");
        String[] strings = /some strings to translate
        for (String data: strings) {
            $x("//textarea[@id='source']").clear();
            $x("//textarea[@id='source']").sendKeys(data);
            String translation = $x("//span[@class='tlid-translation translation']").getText();
        }
    }
}

Solution 5

You can use Google Translate API v2 Java. It has a core module that you can call from your Java code and also a command line interface module.

Share:
123,230
user1048999
Author by

user1048999

Updated on July 12, 2022

Comments

  • user1048999
    user1048999 almost 2 years

    If I pass a string (either in English or Arabic) as an input to the Google Translate API, it should translate it into the corresponding other language and give the translated string to me.

    I read the same case in a forum but it was very hard to implement for me.
    I need the translator without any buttons and if I give the input string it should automatically translate the value and give the output.

    Can you help out?

  • Tapa Save
    Tapa Save almost 10 years
    java-google-translate-text-to-speech translate between English and another languages (mostly). In case translate from 'Russian' to 'Estonian' I get '? ? ? ' answers. You can translate 'Russian'->'English'->'Estonian' and this will work correct, but this way not always right in semantic rules.
  • jobukkit
    jobukkit almost 10 years
    How can this be free? Is it legit?
  • Ionică Bizău
    Ionică Bizău almost 10 years
    @JopVernooij I have not checked the source code, but I guess it would be so simple to stream data from a page like this: translate.google.com/… (Google Translate Speech: Hello World)
  • jobukkit
    jobukkit almost 10 years
    @IonicãBizãu I don't think that is allowed.
  • Ionică Bizău
    Ionică Bizău almost 10 years
    @JopVernooij Any reason for why it wouldn't be allowed? I am now a lawyer to tell you if it's allowed or not, but it's just a public request to an url.
  • gursahib.singh.sahni
    gursahib.singh.sahni over 9 years
    java.net.SocketException: Permission denied: connect
  • Ionică Bizău
    Ionică Bizău over 9 years
    @anonymous See this. Probably it helps you.
  • gursahib.singh.sahni
    gursahib.singh.sahni over 9 years
    just found it ! ------------------------------------------------- Audio audio = Audio.getInstance(); InputStream sound = audio.getAudio("I am a bus", Language.ENGLISH); audio.play(sound);
  • Ionică Bizău
    Ionică Bizău over 9 years
    Cool, you can also check out my example on GitHub.
  • Mateusz Kaflowski
    Mateusz Kaflowski over 8 years
    I get java.io.IOException: Server returned HTTP response code: 403 for URL from some time. Do you have any solution for that?
  • Ionică Bizău
    Ionică Bizău over 8 years
    @MateuszKaflowski Hmm, could it be that the things were changed since I posted the answer? I'm now a Node.js dev, not really into Java anymore, but contributions in my repo are more than welcome!
  • Ionică Bizău
    Ionică Bizău about 8 years
    @Ran Maybe this helps. Looks more updated.
  • Riyafa Abdul Hameed
    Riyafa Abdul Hameed almost 8 years
    Is it free? Does it require an api key?
  • MosheElisha
    MosheElisha almost 8 years
    The source code can be used freely. It does require an API key - so you will be billed by Google according to the usage.
  • Maksym
    Maksym about 6 years
    it is 100% working. I have just used it one moment ago. What is the issue/error?
  • BullyWiiPlaza
    BullyWiiPlaza about 6 years
    @IonicăBizău: This also doesn't work anymore java.io.IOException: Server returned HTTP response code: 503 for URL: http://translate.google.com/translate_a/t?text=Hello%20World‌​&oe=UTF-8&tl=en&clie‌​nt=z&sl=&ie=UTF-8
  • BullyWiiPlaza
    BullyWiiPlaza about 6 years
    Amazing. The only unofficial but working method I found. :)
  • Sachini Wickramaratne
    Sachini Wickramaratne over 5 years
    Hi, This is an amazing solution. I just also need it to detect the input language. Is there any way I could do that? 'auto' wont work
  • Maksym
    Maksym over 5 years
    Have fixed script. Replaced sourceLang = 'auto' with sourceLang = ''. Now you can translate with such code: translate("", "de", text). And after redeploying your google script do not forget to change "Project version", because it does apply your changes if you do not do it.
  • Maksym
    Maksym over 5 years
    From official google docs: sourceLanguage - the language code in which text is written. If it is set to the empty string, the source language code will be auto-detected
  • Bhagwati Malav
    Bhagwati Malav over 5 years
    @MaksymPecheniuk I used this, it works fine. But i am calling this more than 50k times in a day, so it gives error "too many request in a day". Is there any limition on number of requests here ?
  • Maksym
    Maksym over 5 years
    Yes, there are limitation for 24 hours. But you can create 10 or more google accounts and switch them. I personally have created poo of 30 accounts and scripts for each of them.
  • Alvaro Lemos
    Alvaro Lemos almost 5 years
    This is amazing.
  • Chamithra Thenuwara
    Chamithra Thenuwara almost 5 years
    @Ionică Bizău I'm getting this error message - java.io.IOException: Server returned HTTP response code: 403 for URL: http://translate.google.com.br/translate_a/t?client=t&text=H‌​ello!&hl=en&sl=en&tl‌​=ro&multires=1&prev=‌​btn&ssel=0&tsel=0&sc‌​=1
  • Marcello de Sales
    Marcello de Sales almost 5 years
    Worked like a charm! Thank you! If anyone needs SpringBoot version, here's the request object... ` String url = "script.google.com/macros/s/AKf****xhI/exec?q=" + URLEncoder.encode(text, "UTF-8") + "&target=" + this.to + "&source=" + this.from; String translatedText = restTemplate.getForObject(url, String.class);`
  • DeveloperKurt
    DeveloperKurt about 2 years
    Google seems to have removed the support for this project, it is no longer working.