import java.util.ArrayList;
import com.google.api.translate.Language;
import com.google.api.translate.Translator;
public class Translation {
public static void main(String[] args) {
// Translate a single English String to French
Translator translator = new Translator();
System.out.println("Saying goodbye in French:");
System.out.println(translator.translate("goodbye", Language.ENGLISH, Language.FRENCH));
System.out.println();
}
}
-
1Why doesn't this work? What happens when you run it?Arc676– Arc6762015-11-14 07:24:41 +00:00Commented Nov 14, 2015 at 7:24
-
journaldev.com/1370/…online Thomas– online Thomas2015-11-14 07:25:31 +00:00Commented Nov 14, 2015 at 7:25
-
Saying goodbye in French: Exception in thread "main" java.lang.NoSuchMethodError: com.google.api.translate.Language.getLangCode()Ljava/lang/String; at com.google.api.translate.Translator.constructLangPairQuery(Translator.java:230) at com.google.api.translate.Translator.constructQueryURL(Translator.java:247) at com.google.api.translate.Translator.translate(Translator.java:72) at com.inndata.services.Translation.main(Translation.java:14)Venkatesh Bodapati– Venkatesh Bodapati2015-11-14 07:37:36 +00:00Commented Nov 14, 2015 at 7:37
-
I've never worked with google api's but I think either you're missing a jar library or you don't understand the API fully, you can look at this question for the exception you get stackoverflow.com/questions/3695340/java-nosuchmethoderrorniceman– niceman2015-11-14 08:16:07 +00:00Commented Nov 14, 2015 at 8:16
Add a comment
|
1 Answer
First, Google translate API is a paid service: https://cloud.google.com/pricing/
Second, you have to create your own API key and use the key in your app: https://console.developers.google.com.
The code I am using:
HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
AndroidJsonFactory jsonFactory = AndroidJsonFactory.getDefaultInstance();
Translate.Builder builder = new Translate.Builder(httpTransport, jsonFactory, null);
// need this, otherwise you get warning
builder.setApplicationName("Give a name");
Translate translate = builder.build();
List<String> list = new ArrayList<String>();
// I only add one char to the list
list.add(String.valueOf(word[0]));
Translate.Translations.List request = translate.translations().list(list, "en").setKey("<your_api_key>");
String result = request.execute().getTranslations().get(0).getTranslatedText();
Note: don't know the reason yet, I always got the same error if I use my android API key: "com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden", and the reason says "ipRefererBlocked", but it is fine if I use my Browser Key. Hope someone else can figure out the reason.