Wednesday, February 3, 2016

Calling Google Translation API in Java for free

The official Google translate API is available with a fee but there is a way using which you can call the API with free of cost. The trick is to make  a direct call to  secret translate.googleapis.com API that is internally used by the Google Translate extension for Chrome. Luckily  translate.googleapis.com API doesn't require any authentication. 

Following is the java code to call this API and get your word translation from any Google supported language to other language -


package default;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.JSONArray;

public class Translator {

 public static void main(String[] args) throws Exception 
 {

  Translator http = new Translator();
  String word = http.callUrlAndParseResult("en", "hi", "hello");
  
  System.out.println(word);
 }
 
 private String callUrlAndParseResult(String langFrom, String langTo,
                                             String word) throws Exception 
 {

  String url = "https://translate.googleapis.com/translate_a/single?"+
    "client=gtx&"+
    "sl=" + langFrom + 
    "&tl=" + langTo + 
    "&dt=t&q=" + URLEncoder.encode(word, "UTF-8");    
  
  URL obj = new URL(url);
  HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 
  con.setRequestProperty("User-Agent", "Mozilla/5.0");
 
  BufferedReader in = new BufferedReader(
    new InputStreamReader(con.getInputStream()));
  String inputLine;
  StringBuffer response = new StringBuffer();
 
  while ((inputLine = in.readLine()) != null) {
   response.append(inputLine);
  }
  in.close();
 
  return parseResult(response.toString());
 }
 
 private String parseResult(String inputJson) throws Exception
 {
  /*
   * inputJson for word 'hello' translated to language Hindi from English-
   * [[["नमस्ते","hello",,,1]],,"en"]
   * We have to get 'नमस्ते ' from this json.
   */
  
  JSONArray jsonArray = new JSONArray(inputJson);
  JSONArray jsonArray2 = (JSONArray) jsonArray.get(0);
  JSONArray jsonArray3 = (JSONArray) jsonArray2.get(0);
  
  return jsonArray3.get(0).toString();
 }
}

You can download org.json jar from here.

If you are seeing garbage looking characters in output then you will have to set character encoding as "UTF-8" in your Java Project. This happens when output language is of unicode type. You can set character encoding from Project Properties -> Resource -> Text file encoding. Following is the screenshot to help you in this -



Please feel free to comment below if you have any doubts.

29 comments:

  1. Hey Archana....You are awwweesommme!.....Thanks for this.

    ReplyDelete
  2. Hi, English to Hindi is working fine. But when I am converting from Hindi to English, I am getting junk character. [[["ठ• à ¥ या हाल","कॠया हाल",,,0]],,"hi"]. Can you help me on this?

    ReplyDelete
  3. Hi Praful,
    You have to set "Text file encoding property" to UTF-8. By default it is not UTF-8, that is why you are seeing junk characters.

    See last paragraph of this article for how to set this property in eclipse.

    ReplyDelete
  4. Hi Archana, thanks for the reply. I have set the Text file encoding property to UTF-8. Still I am getting junk character. See the response below:

    Language Transormation url : https://translate.googleapis.com/translate_a/single?client=gtx&sl=hi&tl=en&dt=t&q=%E0%A4%95%E0%A5%8D%E0%A4%AF%E0%A4%BE+%E0%A4%B9%E0%A4%BE%E0%A4%B2
    statusCode : 200
    response_string : [[["ठ• à ¥ या हाल","कॠया हाल",,,0]],,"hi"]

    ReplyDelete
  5. Set User Agent property. Its working now. Thanks. Actually I was not using Java.net instead I was using org.Apache package. There I need to addHeader instead of setRequestProperty.

    ReplyDelete
    Replies
    1. Thanks Praful for reverting back. Can you please share what user agent you set so that I can update the blog for other's reference?

      Delete
    2. May i know how to setup the user agent in java? I would like to convert english to chinese.

      Delete
  6. This small snippet of code saves a lot! Such a great trick, google api translator is a paid service. Translating 1 million characters costs 20$. There is a whole set of process for registration. .

    ReplyDelete
  7. Hi, I have tried your code and it actually returned empty strings. Any idea what is going on?
    [[["",""]],null,"en"]

    ReplyDelete
  8. Its working man. thanks a lot for sharinf

    ReplyDelete
  9. hello ,
    i am translating from english to arabic it works well with all letters except one letter it shows 'ف' as '�?'
    any suggestions ?

    public static void main(String[] args) {
    try {
    String word = callUrlAndParseResult("en", "ar", "rat");
    System.out.println(new String(word.getBytes(), Charset.forName("UTF-8")));
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

    ReplyDelete
  10. your kind help is appreciated, saved me lots of time and efforts

    Thank you :)

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. if you want many strings translation, use

    private fun parseResult(inpJson: String): String {
    val jsonArray = JSONArray(inpJson)
    Timber.d("jsp inpJson: $inpJson")
    val jsonArray2 = jsonArray.get(0) as JSONArray

    Timber.d("jsp length of array: ${jsonArray2.length()}")
    var resStr = ""
    val size=jsonArray2.length()
    (0 until size).forEach { i->
    resStr+=(jsonArray2.get(i) as JSONArray).get(0).toString()
    }

    return resStr
    }

    ReplyDelete
  13. Thanks alot its working. Is it a paid service or its free?

    ReplyDelete
  14. Its working fine but i am getting problem when i pass long character then its convert some start character ,how to solve this type probleam

    ReplyDelete
    Replies
    1. Replace parseResult method with this

      private String parseResult(String inputJson) throws Exception {

      JSONArray jsonArray = new JSONArray(inputJson);
      JSONArray jsonArray2 = (JSONArray) jsonArray.get(0);
      String s = "";

      for (int i = 0; i < jsonArray2.length(); i++) {
      JSONArray array_element = (JSONArray) jsonArray2.get(i);
      s += (String) array_element.get(0);

      }

      return s;
      }

      Delete
  15. HI Archana,

    After translating around 55K records the api throws 503 forbidden error. Any idea how to pass through.

    ReplyDelete
  16. Wonderful blog. Keep sharing like this useful information thanks for sharing your valuable blog.arabic translation services

    ReplyDelete
  17. thx, very helpful.
    i got similar problem with Praful Dhone,but with chinese.
    after change User-Agent from mozilla to Mozilla/5.0, problem solved

    ReplyDelete
  18. when I am converting a lot of words to convert it is saying

    Exception in thread "main" java.io.IOException: Server returned HTTP response code: 429 for URL: https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=hi&dt=t&q=hello

    ReplyDelete
  19. same code for me not working

    ReplyDelete
  20. hello mam,when i use this code for hindi language,its working when i use main method in java code ,but not working with jsp servlet
    please help me

    ReplyDelete
  21. Excellent solution.. you saved me.. Thank you

    ReplyDelete
  22. url not working properly.(java.io.IOException: Server returned HTTP response code: 429 for URL: https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=mr&dt).Please help.

    ReplyDelete
  23. i needed this code will work in offline(without internet) mode also

    ReplyDelete
  24. How to Make Money with Money Betting - Work-to-Earn
    Money หารายได้เสริม Betting is the simplest form of sports betting 메리트 카지노 in which 메리트 카지노 주소 you bet on whether the outcome of a game is going to win or lose. However, some bettors

    ReplyDelete