如何Google翻译API,当我尝试不提供正确的输出
答
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密钥。您不应该直接在代码中直接放置这些键。 –
如果您提供了您试过的代码会很有帮助... –