1
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();
    }
}
4
  • 1
    Why doesn't this work? What happens when you run it? Commented Nov 14, 2015 at 7:24
  • journaldev.com/1370/… Commented 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) Commented 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-nosuchmethoderror Commented Nov 14, 2015 at 8:16

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.