How to use Google Translate API in my Java application?

后端 未结 5 1015
攒了一身酷
攒了一身酷 2020-11-27 12:58

If I pass a string (either in English or Arabic) as an input to the Google Translate API, it should translate it into the corresponding other language and give the translate

5条回答
  •  暖寄归人
    2020-11-27 13:41

    Generate your own API key here. Check out the documentation here.

    You may need to set up a billing account when you try to enable the Google Cloud Translation API in your account.

    Below is a quick start example which translates two English strings to Spanish:

    import java.io.IOException;
    import java.security.GeneralSecurityException;
    import java.util.Arrays;
    
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.services.translate.Translate;
    import com.google.api.services.translate.model.TranslationsListResponse;
    import com.google.api.services.translate.model.TranslationsResource;
    
    public class QuickstartSample
    {
        public static void main(String[] arguments) throws IOException, GeneralSecurityException
        {
            Translate t = new Translate.Builder(
                    GoogleNetHttpTransport.newTrustedTransport()
                    , GsonFactory.getDefaultInstance(), null)
                    // Set your application name
                    .setApplicationName("Stackoverflow-Example")
                    .build();
            Translate.Translations.List list = t.new Translations().list(
                    Arrays.asList(
                            // Pass in list of strings to be translated
                            "Hello World",
                            "How to use Google Translate from Java"),
                    // Target language
                    "ES");
    
            // TODO: Set your API-Key from https://console.developers.google.com/
            list.setKey("your-api-key");
            TranslationsListResponse response = list.execute();
            for (TranslationsResource translationsResource : response.getTranslations())
            {
                System.out.println(translationsResource.getTranslatedText());
            }
        }
    }
    

    Required maven dependencies for the code snippet:

    
        com.google.cloud
        google-cloud-translate
        LATEST
    
    
    
        com.google.http-client
        google-http-client-gson
        LATEST
    
    

提交回复
热议问题