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.
Hey Archana....You are awwweesommme!.....Thanks for this.
ReplyDeleteHi, 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?
ReplyDeleteHi Praful,
ReplyDeleteYou 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.
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:
ReplyDeleteLanguage 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"]
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.
ReplyDeleteThanks Praful for reverting back. Can you please share what user agent you set so that I can update the blog for other's reference?
DeleteMay i know how to setup the user agent in java? I would like to convert english to chinese.
DeleteThis 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. .
ReplyDeleteHi, I have tried your code and it actually returned empty strings. Any idea what is going on?
ReplyDelete[[["",""]],null,"en"]
Its working man. thanks a lot for sharinf
ReplyDeletehello ,
ReplyDeletei 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());
}
}
your kind help is appreciated, saved me lots of time and efforts
ReplyDeleteThank you :)
This comment has been removed by the author.
ReplyDeleteif you want many strings translation, use
ReplyDeleteprivate 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
}
Thanks alot its working. Is it a paid service or its free?
ReplyDeleteValuable for information if there is any other regarding this kindly revert me back on this
ReplyDeletelegal translation in Dubai
Certificate attestation for UAE
Interpretation services Dubai
Legal translation services in Dubai
Translate English to Arabic Dubai
Professional Interpreters Dubai
Legal Translation Dubai
Certificate attestation for UAE
Interpretation services Dubai
Legal Translation Dubai
Translate English to Arabic Dubai
Interpretation services Dubai
Legal translation services in Dubai
Certificate attestation for UAE
Interpretation services Dubai
Legal Translation Dubai
Translate English to Arabic Dubai
Interpretation services Dubai
legal translation in Dubai
Certificate attestation for UAE
Interpretation services Dubai
Legal translation services in Dubai
Translate English to Arabic Dubai
Interpretation services Dubai
Legal Translation Dubai
Certificate attestation for UAE
Interpretation services Dubai
legal translation in Dubai
Translate English to Arabic Dubai
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
ReplyDeleteReplace parseResult method with this
Deleteprivate 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;
}
HI Archana,
ReplyDeleteAfter translating around 55K records the api throws 503 forbidden error. Any idea how to pass through.
Wonderful blog. Keep sharing like this useful information thanks for sharing your valuable blog.arabic translation services
ReplyDeletethx, very helpful.
ReplyDeletei got similar problem with Praful Dhone,but with chinese.
after change User-Agent from mozilla to Mozilla/5.0, problem solved
when I am converting a lot of words to convert it is saying
ReplyDeleteException 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
facing the same issue, any solution ?
Deletesame code for me not working
ReplyDeletehello 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
ReplyDeleteplease help me
Excellent solution.. you saved me.. Thank you
ReplyDeleteurl 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.
ReplyDeletei needed this code will work in offline(without internet) mode also
ReplyDeleteHow to Make Money with Money Betting - Work-to-Earn
ReplyDeleteMoney หารายได้เสริม 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