Java百度翻译API中⽂转英⽂接⼊
Java 百度翻译 API 中⽂转英⽂接⼊
业务上遇到了语⾔国际化的需求,需要将中⽂的 json 字符串翻译成英⽂,通过百度翻译 API 接⼝来实现翻译功能。
1、平台认证
登录百度翻译开放平台,到通⽤翻译模块,提交申请。
申请通过后,就能直接使⽤了,默认为标准版,完全免费:
2、Java demo 配置
翻译开放平台⾮常友好,提供了许多常⽤语⾔的 demo 下载,稍微修改下便能使⽤了。
demo 配置好 appid 及密钥,运⾏便能看到控制台中⽂成功翻译成了英⽂:
3、封装接⼝
我的⽬标是将⼀长串的中⽂ json 翻译成英⽂ json, 上⾯的 demo 是满⾜不了需求的,可以创建⼀个 springboot 项⽬,将 demo 代码迁移到项⽬中,封装⼀个接⼝实现业务需求。
项⽬结构如下:
3.1、⾃定义接⼝
先引⼊fastJson依赖:
<!--fastJson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
接⼝参数接收⼀长串的中⽂ json ,翻译完成后返回英⽂ json:
3.1.1、直接创建线程版本
package ller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import fig.TransApi;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.UnsupportedEncodingException;
import java.URLDecoder;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/com/lin")
public class TranslateController {
// 在平台申请的APP_ID 详见 api.fanyi.baidu/api/trans/product/desktop?req=developer
private static final String APP_ID = "";
private static final String SECURITY_KEY = "";
@GetMapping("/translate")
@ResponseBody
public Map<String, Map<String, String>> toTranslate(@RequestBody Map<String, Map<String, String>> map) throws InterruptedException {
TransApi api = new TransApi(APP_ID, SECURITY_KEY);
for(String key : map.keySet()) {
Map<String, String> childMap = (key);
StringBuilder builder = new StringBuilder();
for (String childKey : childMap.keySet()) {
//需要翻译的中⽂
builder.(childKey)).append("\n");
}
//创建线程
Thread thread = new Thread() {
@Override
public void run() {
String result = String(), "auto", "en");
System.out.println(result);
//转成map
Map<String, String> mapResult = JSON.parseObject(result, Map.class);
List<Map<String, String>> transResult = (List<Map<String, String>>)JSONArray.("trans_result"))); int i = 0;
for (String childKey : childMap.keySet()) {
//获取翻译结果
String transQuery = (i).get("dst");
try {
//解码
transQuery= URLDecoder.decode(transQuery,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
childMap.put(childKey, transQuery);
i++;
}
try {
//睡眠⼀秒
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
//主线程阻塞,等待⼦线程结束
thread.join();
}
return map;
}
}
3.1.2、线程池版本
package ller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import fig.TransApi;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.UnsupportedEncodingException;
import java.URLDecoder;
import java.util.List;
import java.util.Map;
import urrent.*;
@Controller
@RequestMapping("/com/lin")
public class ExecutorController {
// 在平台申请的APP_ID 详见 api.fanyi.baidu/api/trans/product/desktop?req=developer
private static final String APP_ID = "";
private static final String SECURITY_KEY = "";
@GetMapping("/executorTranslate")
@ResponseBody
public Map<String, Map<String, String>> toTranslate(@RequestBody Map<String, Map<String, String>> map) throws InterruptedException {
TransApi api = new TransApi(APP_ID, SECURITY_KEY);
//创建线程池,核⼼线程1,最⼤线程数10,存货时间1分钟,任务队列5,默认的线程⼯⼚,拒绝策略为拒绝并抛出异常
ExecutorService executorService = new ThreadPoolExecutor(1, 10, 1, TimeUnit.MINUTES,
new ArrayBlockingQueue<>(5, true), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
for (String key : map.keySet()) {
Map<String, String> childMap = (key);
StringBuilder builder = new StringBuilder();
for (String childKey : childMap.keySet()) {
//需要翻译的中⽂
builder.(childKey)).append("\n");
}
//执⾏线程
String result = String(), "auto", "en");
System.out.println("result:" + result);
//转成map
Map<String, String> mapResult = JSON.parseObject(result, Map.class);
List<Map<String, String>> transResult = (List<Map<String, String>>) JSONArray.("trans_result"))); int i = 0;
for (String childKey : childMap.keySet()) {
//获取翻译结果
String transQuery = (i).get("dst");
try {
//解码
transQuery = URLDecoder.decode(transQuery, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
childMap.put(childKey, transQuery);
i++;
}
});
//线程池等待时间,这⾥即阻塞2秒
executorService.awaitTermination(2, TimeUnit.SECONDS);
}
//任务执⾏完成后关闭线程池
executorService.shutdown();
return map;
}
}
3.2、demo 配置类代码
HttpGet 类代码如下:
package anslate.demo;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.HttpURLConnection;
import java.MalformedURLException;
import java.URL;
import java.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import CertificateException;
import X509Certificate;
import java.util.Map;
import javax.ssl.HttpsURLConnection;
import javax.ssl.SSLContext;
import javax.ssl.TrustManager;
import javax.ssl.X509TrustManager;
class HttpGet {
protected static final int SOCKET_TIMEOUT = 10000; // 10S
protected static final String GET = "GET";
public static String get(String host, Map<String, String> params) {
try {
// 设置SSLContext
SSLContext sslcontext = Instance("TLS");
sslcontext.init(null, new TrustManager[] { myX509TrustManager }, null);
String sendUrl = getUrlWithQueryString(host, params);
// System.out.println("URL:" + sendUrl);
URL uri = new URL(sendUrl); // 创建URL对象
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
if (conn instanceof HttpsURLConnection) {
((HttpsURLConnection) conn).SocketFactory());
}
conn.setConnectTimeout(SOCKET_TIMEOUT); // 设置相应超时
conn.setRequestMethod(GET);
int statusCode = ResponseCode();
if (statusCode != HttpURLConnection.HTTP_OK) {
System.out.println("Http错误码:" + statusCode);
}
// 读取服务器的数据
InputStream is = InputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
builder.append(line);
}
String text = String();
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;
}
public static String getUrlWithQueryString(String url, Map<String, String> params) { if (params == null) {
return url;
}
StringBuilder builder = new StringBuilder(url);
if (ains("?")) {
builder.append("&");
} else {
builder.append("?");
}
int i = 0;
for (String key : params.keySet()) {
String value = (key);
if (value == null) { // 过滤空的key
continue;
}
if (i != 0) {
builder.append('&');
}
builder.append(key);
builder.append('=');
builder.append(encode(value));
i++;
下载翻译器英文翻中文}
String();
}
protected static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 对输⼊的字符串进⾏URL编码, 即转换为%20这种形式
*
* @param input 原⽂
* @return URL编码. 如果编码失败, 则返回原⽂
*/
public static String encode(String input) {
if (input == null) {
return "";
}
try {
de(input, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return input;
}
private static 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 { }
};
}
MD5 类代码如下:
package fig;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5编码相关的类
*
* @author wangjingtao
*
*/
public class MD5 {
// ⾸先初始化⼀个字符数组,⽤来存放每个16进制字符
private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f' };
/**
* 获得⼀个字符串的MD5值
*
* @param input 输⼊的字符串
* @return 输⼊字符串的MD5值
*
*/
public static String md5(String input) {
if (input == null) {
return null;
}
try {
// 拿到⼀个MD5转换器(如果想要SHA1参数换成”SHA1”)
MessageDigest messageDigest = Instance("MD5");
// 输⼊的字符串转换成字节数组
byte[] inputByteArray = Bytes("utf-8");
// inputByteArray是输⼊字符串转换得到的字节数组
messageDigest.update(inputByteArray);
// 转换并返回结果,也是字节数组,包含16个元素
byte[] resultByteArray = messageDigest.digest();
// 字符数组转换成字符串返回
return byteArrayToHex(resultByteArray);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
/**
* 获取⽂件的MD5值
*
* @param file
* @return
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论