How to use Google Translate API in my Java application?

后端 未结 5 1025
攒了一身酷
攒了一身酷 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:31

    You can use google script which has FREE translate API. All you need is a common google account and do these THREE EASY STEPS.
    1) Create new script with such code on google script:

    var mock = {
      parameter:{
        q:'hello',
        source:'en',
        target:'fr'
      }
    };
    
    
    function doGet(e) {
      e = e || mock;
    
      var sourceText = ''
      if (e.parameter.q){
        sourceText = e.parameter.q;
      }
    
      var sourceLang = '';
      if (e.parameter.source){
        sourceLang = e.parameter.source;
      }
    
      var targetLang = 'en';
      if (e.parameter.target){
        targetLang = e.parameter.target;
      }
    
      var translatedText = LanguageApp.translate(sourceText, sourceLang, targetLang, {contentType: 'html'});
    
      return ContentService.createTextOutput(translatedText).setMimeType(ContentService.MimeType.JSON);
    }
    

    2) Click Publish -> Deploy as webapp -> Who has access to the app: Anyone even anonymous -> Deploy. And then copy your web app url, you will need it for calling translate API.

    3) Use this java code for testing your API:

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    
    public class Translator {
    
        public static void main(String[] args) throws IOException {
            String text = "Hello world!";
            //Translated text: Hallo Welt!
            System.out.println("Translated text: " + translate("en", "de", text));
        }
    
        private static String translate(String langFrom, String langTo, String text) throws IOException {
            // INSERT YOU URL HERE
            String urlStr = "https://your.google.script.url" +
                    "?q=" + URLEncoder.encode(text, "UTF-8") +
                    "&target=" + langTo +
                    "&source=" + langFrom;
            URL url = new URL(urlStr);
            StringBuilder response = new StringBuilder();
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            return response.toString();
        }
    
    }
    

    As it is free, there are QUATA LIMITS: https://docs.google.com/macros/dashboard

提交回复
热议问题