import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* 翻译工具类
*/
@Slf4j
public class TranslateUtil {
private final static Logger logger = LoggerFactory.getLogger(TranslateUtil.class);
/**
* 处理返回的错误信息
*
* @param message - 错误信息
* @return
*/
public static String trans(String message){
if (message == null || message == ""){
return "未知的信息!";
}
JSONObject data = JSONObject.parseObject(google(message));
if (data == null){
return "未知的信息!";
}
JSONArray sentences = JSONArray.parseArray(data.get("sentences").toString());
JSONObject trans = JSONObject.parseObject(JSON.toJSONString(sentences.get(0)));
return trans.getString("trans").replace(" ", "");
}
/**
* 谷歌翻译
*
* @param text - 文本
* @return
*/
public static String google(String text){
if (text.contains(" ")) {
text.replace(" ", "%20");
}
String url = "https://translate.googleapis.com/translate_a/single";
String param = null;
String result = null;
try {
param = "client=gtx&dt=t&dj=1&ie=UTF-8&sl=en&tl=zh_TW&q=" + URLEncoder.encode(text, "UTF-8");
result = HttpRequestClient.sendGet(url, param);
log.info("翻譯結果:" + result);
} catch (UnsupportedEncodingException e) {
logger.info("Google.translate Error!");
}
return result;
}
}