Google translate API 调用方法
锺离嘉容
2023-12-01
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package framework.webapp.commons.utils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
/**
*
* @author mly
*/
public class GoogleTranslate {
private String key;
public GoogleTranslate(String apiKey) {
key = apiKey;
}
String translte(String text, String to) {
StringBuilder result = new StringBuilder();
try {
String encodedText = URLEncoder.encode(text, "UTF-8");
String urlStr = "https://www.googleapis.com/language/translate/v2?key=" + key + "&q=" + encodedText + "&target=" + to;
//https://www.googleapis.com/language/translate/v2?key=AIzaSyD6ly_S2TjlglpJZgqpiXw3q2B8WcU_AAo&q=cat&source=en&target=zh-CN
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
InputStream stream;
//设置代理服务器
System.getProperties().put("proxySet", SystemConfig.getProperty("proxyEnable"));
System.getProperties().put("proxyHost", SystemConfig.getProperty("network.proxy.http"));
System.getProperties().put("proxyPort", SystemConfig.getProperty("network.proxy.http_port"));
if (conn.getResponseCode() == 200) //success
{
stream = conn.getInputStream();
} else
stream = conn.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result.toString());
if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
if (obj.get("error") == null) {
String translatedText = obj.get("data").getAsJsonObject().
get("translations").getAsJsonArray().
get(0).getAsJsonObject().
get("translatedText").getAsString();
return translatedText;
}
}
if (conn.getResponseCode() != 200) {
System.err.println(result);
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
return null;
}
public String detect(String text){
StringBuilder result = new StringBuilder();
try {
String encodedText = URLEncoder.encode(text, "UTF-8");
String urlStr = "https://www.googleapis.com/language/translate/v2/detect?key=" + key + "&q=" +encodedText;
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
InputStream stream;
//设置代理服务器
System.getProperties().put("proxySet", SystemConfig.getProperty("proxyEnable"));
System.getProperties().put("proxyHost", SystemConfig.getProperty("network.proxy.http"));
System.getProperties().put("proxyPort", SystemConfig.getProperty("network.proxy.http_port"));
if (conn.getResponseCode() == 200) //success
{
stream = conn.getInputStream();
} else
stream = conn.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result.toString());
if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
if (obj.get("error") == null) {
String detectedText = obj.get("data").getAsJsonObject().
get("detections").getAsJsonArray().
get(0).getAsJsonArray().get(0).getAsJsonObject().get("language").getAsString();
return detectedText;
}
}
if (conn.getResponseCode() != 200) {
System.err.println(result);
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
return null;
}
public static void main(String[] args) {
GoogleTranslate translator = new GoogleTranslate("AIzaSyDdhoxnh2zfOevD4pHbUFlY6lBjQHdk9-Y");
// String text = translator.translte("中国", "en");
String text = translator.detect("中国Nghề nghiệp");
System.out.println(text);
}
}