How to use Google Translate API in my Java application?
Asked Answered
M

5

42

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?

Mercurial answered 16/11, 2011 at 5:48 Comment(1)
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.Carminacarminative
G
58

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

Gisela answered 9/1, 2018 at 0:25 Comment(10)
it is 100% working. I have just used it one moment ago. What is the issue/error?Gisela
Amazing. The only unofficial but working method I found. :)Visigoth
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 workInvincible
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.Gisela
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-detectedGisela
@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 ?Forcible
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.Gisela
This is amazing.Roth
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);`Jimmy
@Maksym, it's not working for me, getting HTML content in the response. Not translating textUdell
D
26

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

Dastardly answered 1/5, 2013 at 19:34 Comment(15)
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.Corselet
How can this be free? Is it legit?Verge
@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)Parvis
@IonicãBizãu I don't think that is allowed.Verge
@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.Parvis
java.net.SocketException: Permission denied: connectCasefy
@anonymous See this. Probably it helps you.Parvis
just found it ! ------------------------------------------------- Audio audio = Audio.getInstance(); InputStream sound = audio.getAudio("I am a bus", Language.ENGLISH); audio.play(sound);Casefy
Cool, you can also check out my example on GitHub.Parvis
I get java.io.IOException: Server returned HTTP response code: 403 for URL from some time. Do you have any solution for that?Subscribe
@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!Parvis
@Ran Maybe this helps. Looks more updated.Parvis
@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&client=z&sl=&ie=UTF-8Visigoth
@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=Hello!&hl=en&sl=en&tl=ro&multires=1&prev=btn&ssel=0&tsel=0&sc=1Nunn
Google seems to have removed the support for this project, it is no longer working.Geriatrics
S
11

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>
Scever answered 8/12, 2016 at 0:16 Comment(0)
N
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();
        }
    }
}
Nev answered 31/8, 2019 at 17:32 Comment(0)
P
3

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.

Paganism answered 30/11, 2011 at 6:33 Comment(2)
Is it free? Does it require an api key?Ream
The source code can be used freely. It does require an API key - so you will be billed by Google according to the usage.Paganism

© 2022 - 2024 — McMap. All rights reserved.