Java百度翻译API中⽂转英⽂接⼊
Java百度翻译API中⽂转英⽂接⼊
业务上遇到了语⾔国际化的需求,需要将中⽂的json字符串翻译成英⽂,通过百度翻译API接⼝来实现翻译功能。
1、平台认证
登录百度翻译开放平台,找到通⽤翻译模块,提交申请。
申请通过后,就能直接使⽤了,默认为标准版,完全免费:
2、Javademo配置
翻译开放平台⾮常友好,提供了许多常⽤语⾔的demo下载,稍微修改下便能使⽤了。
demo配置好appid及密钥,运⾏便能看到控制台中⽂成功翻译成了英⽂:
3、封装接⼝
我的⽬标是将⼀长串的中⽂json翻译成英⽂json,上⾯的demo是满⾜不了需求的,可以创建⼀个springboot项⽬,将demo代码迁移到
项⽬中,封装⼀个接⼝实现业务需求。
项⽬结构如下:
3.1、⾃定义接⼝
先引⼊fastJson依赖:
接⼝参数接收⼀长串的中⽂json,翻译完成后返回英⽂json:
3.1.1、直接创建线程版本
ller;
;
ray;
pi;
ller;
ping;
tBody;
tMapping;
Body;
ortedEncodingException;
oder;
;
;
@Controller
@RequestMapping("/com/lin")
publicclassTranslateController{
//在平台申请的APP_ID详见/api/trans/product/desktop?req=developer
privatestaticfinalStringAPP_ID="";
privatestaticfinalStringSECURITY_KEY="";
@GetMapping("/translate")
@ResponBody
publicMap
TransApiapi=newTransApi(APP_ID,SECURITY_KEY);
for(Stringkey:()){
Map
StringBuilderbuilder=newStringBuilder();
for(StringchildKey:()){
//需要翻译的中⽂
((childKey)).append("n");
}
//创建线程
Threadthread=newThread(){
@Override
publicvoidrun(){
Stringresult=nsResult(ng(),"auto","en");
n(result);
//转成map
Map
List
inti=0;
for(StringchildKey:()){
//获取翻译结果
StringtransQuery=(i).get("dst");
try{
//解码
transQuery=(transQuery,"utf-8");
}catch(UnsupportedEncodingExceptione){
tackTrace();
}
(childKey,transQuery);
i++;
}
try{
//睡眠⼀秒
(1000);
}catch(InterruptedExceptione){
tackTrace();
}
}
};
();
//主线程阻塞,等待⼦线程结束
();
}
returnmap;
}
}
3.1.2、线程池版本
ller;
;
ray;
pi;
ller;
ping;
tBody;
tMapping;
Body;
ortedEncodingException;
oder;
;
;
rent.*;
@Controller
@RequestMapping("/com/lin")
publicclassExecutorController{
//在平台申请的APP_ID详见/api/trans/product/desktop?req=developer
privatestaticfinalStringAPP_ID="";
privatestaticfinalStringSECURITY_KEY="";
@GetMapping("/executorTranslate")
@ResponBody
publicMap
TransApiapi=newTransApi(APP_ID,SECURITY_KEY);
//创建线程池,核⼼线程1,最⼤线程数10,存货时间1分钟,任务队列5,默认的线程⼯⼚,拒绝策略为拒绝并抛出异常
ExecutorServiceexecutorService=newThreadPoolExecutor(1,10,1,S,
newArrayBlockingQueue<>(5,true),tThreadFactory(),olicy());
for(Stringkey:()){
Map
StringBuilderbuilder=newStringBuilder();
for(StringchildKey:()){
//需要翻译的中⽂
((childKey)).append("n");
}
//执⾏线程
e(()->{
Stringresult=nsResult(ng(),"auto","en");
n("result:"+result);
//转成map
Map
List
inti=0;
for(StringchildKey:()){
//获取翻译结果
StringtransQuery=(i).get("dst");
try{
//解码
transQuery=(transQuery,"utf-8");
}catch(UnsupportedEncodingExceptione){
tackTrace();
}
(childKey,transQuery);
i++;
}
});
//线程池等待时间,这⾥即阻塞2秒
ermination(2,S);
}
//任务执⾏完成后关闭线程池
wn();
returnmap;
}
}
3.2、demo配置类代码
HttpGet类代码如下:
;
edReader;
ble;
ption;
tream;
treamReader;
ortedEncodingException;
LConnection;
medURLException;
;
oder;
agementException;
AlgorithmException;
icateException;
.X509Certificate;
;
RLConnection;
text;
anager;
.X509TrustManager;
classHttpGet{
protectedstaticfinalintSOCKET_TIMEOUT=10000;//10S
protectedstaticfinalStringGET="GET";
publicstaticStringget(Stringhost,Map
try{
//设置SSLContext
SSLContextsslcontext=tance("TLS");
(null,newTrustManager[]{myX509TrustManager},null);
StringndUrl=getUrlWithQueryString(host,params);
//n("URL:"+ndUrl);
URLuri=newURL(ndUrl);//创建URL对象
HttpURLConnectionconn=(HttpURLConnection)nnection();
if(conninstanceofHttpsURLConnection){
((HttpsURLConnection)conn).tSSLSocketFactory(ketFactory());
}
nectTimeout(SOCKET_TIMEOUT);//设置相应超时
uestMethod(GET);
intstatusCode=ponCode();
if(statusCode!=_OK){
n("Http错误码:"+statusCode);
}
//读取服务器的数据
InputStreamis=utStream();
BufferedReaderbr=newBufferedReader(newInputStreamReader(is));
StringBuilderbuilder=newStringBuilder();
Stringline=null;
while((line=ne())!=null){
(line);
}
Stringtext=ng();
clo(br);//关闭数据流
clo(is);//关闭数据流
nect();//断开连接
returntext;
}catch(MalformedURLExceptione){
tackTrace();
}catch(IOExceptione){
tackTrace();
}catch(KeyManagementExceptione){
tackTrace();
}catch(NoSuchAlgorithmExceptione){
tackTrace();
}
returnnull;
}
publicstaticStringgetUrlWithQueryString(Stringurl,Map
if(params==null){
returnurl;
}
StringBuilderbuilder=newStringBuilder(url);
if(ns("?")){
("&");
}el{
("?");
}
inti=0;
for(Stringkey:()){
Stringvalue=(key);
if(value==null){//过滤空的key
continue;
}
if(i!=0){
('&');
}
(key);
('=');
(encode(value));
i++;
}
ng();
}
protectedstaticvoidclo(Cloablecloable){
if(cloable!=null){
try{
();
}catch(IOExceptione){
tackTrace();
}
}
}
/**
*对输⼊的字符串进⾏URL编码,即转换为%20这种形式
*
*@paraminput原⽂
*@returnURL编码.如果编码失败,则返回原⽂
*/
publicstaticStringencode(Stringinput){
if(input==null){
return"";
}
try{
(input,"utf-8");
}catch(UnsupportedEncodingExceptione){
tackTrace();
}
returninput;
}
privatestaticTrustManagermyX509TrustManager=newX509TrustManager(){
@Override
publicX509Certificate[]getAcceptedIssuers(){
returnnull;
}
@Override
publicvoidcheckServerTrusted(X509Certificate[]chain,StringauthType)throwsCertificateException{
}
@Override
publicvoidcheckClientTrusted(X509Certificate[]chain,StringauthType)throwsCertificateException{
}
};
}
MD5类代码如下:
;
.*;
eDigest;
AlgorithmException;
/**
*MD5编码相关的类
*
*@authorwangjingtao
*
*/
publicclassMD5{
//⾸先初始化⼀个字符数组,⽤来存放每个16进制字符
privatestaticfinalchar[]hexDigits={'0','1','2','3','4','5','6','7','8','9','a','b','c','d',
'e','f'};
/**
*获得⼀个字符串的MD5值
*
*@paraminput输⼊的字符串
*@return输⼊字符串的MD5值
*
*/
publicstaticStringmd5(Stringinput){
if(input==null){
returnnull;
}
try{
//拿到⼀个MD5转换器(如果想要SHA1参数换成”SHA1”)
MessageDigestmessageDigest=tance("MD5");
//输⼊的字符串转换成字节数组
byte[]inputByteArray=es("utf-8");
//inputByteArray是输⼊字符串转换得到的字节数组
(inputByteArray);
//转换并返回结果,也是字节数组,包含16个元素
byte[]resultByteArray=();
//字符数组转换成字符串返回
returnbyteArrayToHex(resultByteArray);
}catch(NoSuchAlgorithmException|UnsupportedEncodingExceptione){
tackTrace();
returnnull;
}
}
/**
*获取⽂件的MD5值
*
*@paramfile
*@return
*/
publicstaticStringmd5(Filefile){
try{
if(!()){
n("⽂件"+olutePath()+"不存在或者不是⽂件");
returnnull;
}
FileInputStreamin=newFileInputStream(file);
Stringresult=md5(in);
();
returnresult;
}catch(FileNotFoundExceptione){
tackTrace();
}catch(IOExceptione){
tackTrace();
}
returnnull;
}
publicstaticStringmd5(InputStreamin){
try{
MessageDigestmessagedigest=tance("MD5");
byte[]buffer=newbyte[1024];
intread=0;
while((read=(buffer))!=-1){
(buffer,0,read);
}
();
Stringresult=byteArrayToHex(());
returnresult;
}catch(NoSuchAlgorithmExceptione){
tackTrace();
}catch(FileNotFoundExceptione){
tackTrace();
}catch(IOExceptione){
tackTrace();
}
returnnull;
}
privatestaticStringbyteArrayToHex(byte[]byteArray){
//new⼀个字符数组,这个就是⽤来组成结果字符串的(解释⼀下:⼀个byte是⼋位⼆进制,也就是2位⼗六进制字符(2的8次⽅等于16的2次⽅))
char[]resultCharArray=newchar[*2];
//遍历字节数组,通过位运算(位运算效率⾼),转换成字符放到字符数组中去
intindex=0;
for(byteb:byteArray){
resultCharArray[index++]=hexDigits[b>>>4&0xf];
resultCharArray[index++]=hexDigits[b&0xf];
}
//字符数组组合成字符串返回
returnnewString(resultCharArray);
}
}
TransApi类代码如下:
;
p;
;
publicclassTransApi{
privatestaticfinalStringTRANS_API_HOST="/api/trans/vip/translate";
privateStringappid;
privateStringcurityKey;
publicTransApi(Stringappid,StringcurityKey){
=appid;
tyKey=curityKey;
}
publicStringgetTransResult(Stringquery,Stringfrom,Stringto){
Map
(TRANS_API_HOST,params);
}
privateMap
Map
("q",query);
("from",from);
("to",to);
("appid",appid);
//随机数
Stringsalt=f(tTimeMillis());
("salt",salt);
//签名
Stringsrc=appid+query+salt+curityKey;//加密前的原⽂
("sign",5(src));
returnparams;
}
}
3.3、结果⽰例
原中⽂json:
{
"login":{
"login":"登录",
"loginLoading":"登录中...",
"account":"账号",
"password":"密码",
"lang":"语⾔",
"tAddress":"设置服务地址",
"more":"更多"
},
"mDns":{
"local":"局域⽹",
"localText":"内的XYMERP服务",
"uAddress":"当前设置的地址",
"addressUnAvailable":"⽆法连接此服务器",
"tAddressTips":"未设置服务地址,⽴刻设置"
}
}
翻译后的英⽂json:
{
"login":{
"login":"Signin",
"loginLoading":"Loggingin",
"account":"accountnumber",
"password":"password",
"lang":"language",
"tAddress":"Setrviceaddress",
"more":"more"
},
"mDns":{
"local":"LAN",
"localText":"Xymerprvicein",
"uAddress":"Currentlytaddress",
"addressUnAvailable":"Unabletoconnecttothisrver",
"tAddressTips":"Serviceaddressnott,tnow"
}
}
以上结果满⾜我的需求了,不满⾜你们需求的就稍微修改下吧。
本文发布于:2022-12-10 07:35:42,感谢您对本站的认可!
本文链接:http://www.wtabcd.cn/fanwen/fan/88/77796.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |