第三方 - 对接百度翻译开放平台进行翻译
1、代码
package com.wretchant.fredis.support;
import com.alibaba.fastjson.JSON;
import com.wretchant.fredis.util.CharacterUtils;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("ALL")
public class Baidu {
public static final int SOCKET_TIMEOUT = 10 * 1000;
public static final String GET = "GET";
public static final String APPID = "*******";
public static final String APP_SECRET = "******";
public static final String APP_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate";
public static final String RESULT_KEY = "trans_result";
public static final String TRANS_KEY = "dst";
public static class TransApi {
private String handlerJson(String json) {
Map<String, Object> map = JSON.parseObject(json, Map.class);
if (map.containsKey(RESULT_KEY)) {
List<Map<String, Object>> list = (List<Map<String, Object>>) map.get(RESULT_KEY);
if (!list.isEmpty()) {
Map<String, Object> objectMap = list.get(0);
if (objectMap.containsKey(TRANS_KEY)) {
return objectMap.get(TRANS_KEY).toString();
}
}
}
return "";
}
private static String decompose(String query) {
StringBuilder builder = new StringBuilder();
char[] chars = query.toCharArray();
for (char c : chars) {
if (CharacterUtils.isUppercase(c)) {
builder.append(" ");
builder.append(String.valueOf(c).toLowerCase());
} else {
builder.append(c);
}
}
return builder.toString();
}
public String getTransResult(String query) {
query = decompose(query);
String from = "auto";
String to;
if (CharacterUtils.isChinese(query)) {
to = "en";
} else {
to = "zh";
}
Map<String, String> params = buildParams(query, from, to);
String json = HttpGet.get(APP_URL, params);
return handlerJson(json);
}
private Map<String, String> buildParams(String query, String from, String to) {
Map<String, String> params = new HashMap<>();
params.put("q", query);
params.put("from", from);
params.put("to", to);
params.put("appid", APPID);
String salt = String.valueOf(System.currentTimeMillis());
params.put("salt", salt);
String src = APPID + query + salt + APP_SECRET;
params.put("sign", MD5.md5(src));
return params;
}
}
@SuppressWarnings("CloudToolkitUndefineMagicConstant")
public static class HttpGet {
public static String get(String host, Map<String, String> params) {
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null);
String sendUrl = getUrlWithQueryString(host, params);
URL uri = new URL(sendUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
if (conn instanceof HttpsURLConnection) {
((HttpsURLConnection) conn).setSSLSocketFactory(sslcontext.getSocketFactory());
}
conn.setConnectTimeout(SOCKET_TIMEOUT);
conn.setRequestMethod(GET);
int statusCode = conn.getResponseCode();
if (statusCode != HttpURLConnection.HTTP_OK) {
System.out.println("Http错误码:" + statusCode);
}
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
builder.append(line);
}
String text = builder.toString();
close(br);
close(is);
conn.disconnect();
return text;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("CloudToolkitUndefineMagicConstant")
public static String getUrlWithQueryString(String url, Map<String, String> params) {
if (params == null) {
return url;
}
StringBuilder builder = new StringBuilder(url);
if (url.contains("?")) {
builder.append("&");
} else {
builder.append("?");
}
int i = 0;
for (String key : params.keySet()) {
String value = params.get(key);
if (value == null) {
continue;
}
if (i != 0) {
builder.append('&');
}
builder.append(key);
builder.append('=');
builder.append(encode(value));
i++;
}
return builder.toString();
}
protected static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String encode(String input) {
if (input == null) {
return "";
}
try {
return URLEncoder.encode(input, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return input;
}
private static final TrustManager myX509TrustManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
};
}
public static class MD5 {
private static final char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f'};
public static String md5(String input) {
if (input == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
byte[] inputByteArray = input.getBytes(StandardCharsets.UTF_8);
messageDigest.update(inputByteArray);
byte[] resultByteArray = messageDigest.digest();
return byteArrayToHex(resultByteArray);
} catch (NoSuchAlgorithmException e) {
return null;
}
}
public static String md5(File file) {
try {
if (!file.isFile()) {
System.err.println("文件" + file.getAbsolutePath() + "不存在或者不是文件");
return null;
}
FileInputStream in = new FileInputStream(file);
String result = md5(in);
in.close();
return result;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String md5(InputStream in) {
try {
MessageDigest messagedigest = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read = 0;
while ((read = in.read(buffer)) != -1) {
messagedigest.update(buffer, 0, read);
}
in.close();
String result = byteArrayToHex(messagedigest.digest());
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String byteArrayToHex(byte[] byteArray) {
char[] resultCharArray = new char[byteArray.length * 2];
int index = 0;
for (byte b : byteArray) {
resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
resultCharArray[index++] = hexDigits[b & 0xf];
}
return new String(resultCharArray);
}
}
}
2、用法
String transResult = new Baidu.TransApi().getTransResult(selectedText);