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?

Sk8erPeter
  • 6,899
  • 9
  • 48
  • 67
user1048999
  • 421
  • 1
  • 5
  • 3
  • 5
    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. – r0ast3d Nov 16 '11 at 05:49

5 Answers5

56

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

Maksym
  • 2,650
  • 3
  • 32
  • 50
  • 1
    it is 100% working. I have just used it one moment ago. What is the issue/error? – Maksym Feb 03 '18 at 10:48
  • 3
    Amazing. The only unofficial but working method I found. :) – BullyWiiPlaza Mar 06 '18 at 22:50
  • 2
    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 – Sachini Wickramaratne Sep 06 '18 at 10:19
  • 2
    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 Sep 06 '18 at 20:32
  • 1
    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 – Maksym Sep 06 '18 at 20:34
  • 2
    @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 ? – Bhagwati Malav Sep 28 '18 at 09:55
  • 1
    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. – Maksym Sep 28 '18 at 10:11
  • 1
    This is amazing. – Alvaro Lemos May 28 '19 at 10:56
  • 2
    Worked like a charm! Thank you! If anyone needs SpringBoot version, here's the request object... ` String url = "https://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);` – Marcello DeSales Jul 18 '19 at 22:09
  • @Maksym, it's not working for me, getting HTML content in the response. Not translating text – Angad Bansode May 09 '23 at 06:30
25

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

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • 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. – Tapa Save Jun 09 '14 at 19:35
  • How can this be free? Is it legit? – jobukkit Jun 13 '14 at 17:04
  • @JopVernooij I have not checked the source code, but I guess it would be so simple to stream data from a page like this: https://translate.google.com/translate_tts?ie=UTF-8&q=Hello%20World&tl=en&total=1&idx=0&textlen=11&client=t&prev=input (Google Translate Speech: *Hello World*) – Ionică Bizău Jun 13 '14 at 17:09
  • @IonicãBizãu I don't think that is allowed. – jobukkit Jun 13 '14 at 17:10
  • @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. – Ionică Bizău Jun 13 '14 at 17:13
  • java.net.SocketException: Permission denied: connect – gursahib.singh.sahni Jan 27 '15 at 14:42
  • 1
    @anonymous See [this](https://www.google.ro/search?q=java.net.SocketException%3A+Permission+denied%3A+connect&oq=java.net.SocketException%3A+Permission+denied%3A+connect). Probably it helps you. – Ionică Bizău Jan 27 '15 at 14:45
  • just found it ! ------------------------------------------------- **Audio audio = Audio.getInstance(); InputStream sound = audio.getAudio("I am a bus", Language.ENGLISH); audio.play(sound);** – gursahib.singh.sahni Jan 27 '15 at 14:55
  • Cool, you can also check out [my example on GitHub](https://github.com/IonicaBizau/text-to-speech). – Ionică Bizău Jan 27 '15 at 15:05
  • 3
    I get java.io.IOException: Server returned HTTP response code: 403 for URL from some time. Do you have any solution for that? – Mateusz Kaflowski Jan 11 '16 at 14:20
  • @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 Jan 11 '16 at 15:45
  • @Ran Maybe [this](https://github.com/wihoho/java-google-translate-text-to-speech) helps. Looks more updated. – Ionică Bizău Apr 24 '16 at 14:41
  • 1
    @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-8` – BullyWiiPlaza Mar 06 '18 at 22:38
  • @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=1` – Chamithra Thenuwara Jul 15 '19 at 08:58
  • Google seems to have removed the support for this project, it is no longer working. – DeveloperKurt Apr 27 '22 at 22:56
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>
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
Lakshman Kambam
  • 1,498
  • 13
  • 20
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();
        }
    }
}
Lukyanov Mikhail
  • 500
  • 7
  • 17
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.

MosheElisha
  • 1,930
  • 2
  • 22
  • 27