2015-08-16 44 views

回答

0
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 
    } 
} 
+0

完美地使用上述工作。 –

+0

安全說明:不應將API密鑰直接放在代碼中。對於這樣的例子,使用System.getConsole()。readPassword();來讀取輸入。在實際的生產服務器中,您希望從數據庫中檢索API密鑰。您不應該直接在代碼中直接放置這些鍵。 –