有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (1) 个答案

  1. # 1 楼答案

    package com.integrations;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.ProtocolException;
    import java.net.URL;
    import java.net.URLConnection;
    import java.net.URLEncoder;
    
    import org.json.JSONObject;
    
    import com.google.api.GoogleAPI;
    import com.google.api.GoogleAPIException;
    import com.google.api.translate.Language;
    import com.google.api.translate.Translate;
    
    public abstract class TestTranslate {
    
        /**
         * @param args
         * @throws IOException
         * @throws GoogleAPIException
         * */
    
        public static void main(String[] args) throws IOException {
            // AIzaSyDTxHsEHG0-lVoLLJmG_PwT6L91kXiLAG0
    
            URL obj = new URL(
                    "https://www.googleapis.com/language/translate/v2?key=<your api key goes here>&source=en&target=hi&q=how");
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    
            // optional default is GET
            con.setRequestMethod("GET");
                    con.setRequestProperty("content-type", "application/json; charset=UTF-8");
    
                    int responseCode = con.getResponseCode();
                    System.out.println("Response Code : " + responseCode);
    
                    StringWriter writer = new StringWriter();
                    IOUtils.copy(con.getInputStream(), writer, "UTF-8");
    
                    if (responseCode == 200) {
                        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                        String inputLine;
    
                        while ((inputLine = in.readLine()) != null) {
                            response.append(inputLine);
                        }
                        in.close();
                        System.out.println(response);
                    }
    
                    JSONObject org = new JSONObject(writer .toString());
                    JSONObject obj1 = new JSONObject(org.getJSONObject("data").getJSONArray("translations").get(0).toString());
                    System.out.println(obj1.getString("translatedText"));
    
            }
    
    
        enter code here
        }
    }