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.