java 百度翻译工具类 分别有前端和后端的 例子及工具
使用百度翻译接口需要网上申请key,代码里面有URL。
package cn.secure.util;
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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* @Description 百度翻译HTTP
* @ClassName HttpGet
* @author ygc
* @date 2018年6月26日 下午1:58:56
* @version V1.0
* @since JDK 1.8
*/
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 = SSLContext.getInstance("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).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;
}
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) { // 过滤空的key
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();
}
}
}
/**
* 对输入的字符串进行URL编码, 即转换为%20这种形式
*
* @param input 原文
* @return URL编码. 如果编码失败, 则返回原文
*/
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 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 {
}
};
}
//api类
package cn.secure.util;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
/**
* @Description 转化API
* @ClassName TransApi
* @author ygc
* @date 2018年6月26日 下午1:58:41
* @version V1.0
* @since JDK 1.8
*/
public class TransApi {
private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";
private String appid;
private String securityKey;
public TransApi(String appid, String securityKey) {
this.appid = appid;
this.securityKey = securityKey;
}
public String getTransResult(String query, String from, String to) throws UnsupportedEncodingException {
Map<String, String> params = buildParams(query, from, to);
return HttpGet.get(TRANS_API_HOST, params);
}
private Map<String, String> buildParams(String query, String from, String to) throws UnsupportedEncodingException {
Map<String, String> params = new HashMap<String, String>();
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 + securityKey; // 加密前的原文
params.put("sign", MD5.md5(src));
return params;
}
}
Test类
/**
* Project Name D3
* File Name TestBaiduUtil.java
* Package Name cn.secure.util
* Date 2018年6月26日下午12:14:29
* Copyright (c) 2018, [email protected] All Rights Reserved.
*
*/
package cn.secure.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import com.alibaba.fastjson.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**@Description TODO
*
* @ClassName EnglishTranslateBaiduUtil
* @author ygc
* @date 2018年6月26日 下午12:14:29
* @version V1.0
* @since JDK 1.8
*/
public class EnglishTranslateBaiduUtil {
// 在平台申请的APP_ID 详见 http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer
private static final String APP_ID = "20180626000180267";
private static final String SECURITY_KEY = "SwHMdwzocdsLMYPJ4M08";
/**
* EnglistTranslateChinese (解析百度服务器平台返回的相关数据信息 )<br/>
* @param query 填写查询的英文进行翻译
* @return
* @throws UnsupportedEncodingException
* @author ygc
* @since JDK 1.8
*/
public static String EnglistTranslateChinese(String query) throws UnsupportedEncodingException{
TransApi api = new TransApi(APP_ID, SECURITY_KEY);
//英语为 en auto 自动检测
String result=api.getTransResult(query, "anto", "zh");
String date="";
com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
com.alibaba.fastjson.JSONArray array = jsonObject.getJSONArray("trans_result");
int length=array.size();
for(int i=0;i<length;i++){
com.alibaba.fastjson.JSONObject params=JSON.parseObject(array.getString(i));
String str=params.getString("dst");
try {
str=URLDecoder.decode(str,"utf-8");
date=str;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return date;
}
public static String ChineseTranslateEnglist(String query) throws UnsupportedEncodingException{
TransApi api = new TransApi(APP_ID, SECURITY_KEY);
//英语为 en auto 自动检测
String result=api.getTransResult(query, "anto", "en");
String date="";
com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
com.alibaba.fastjson.JSONArray array = jsonObject.getJSONArray("trans_result");
int length=array.size();
for(int i=0;i<length;i++){
com.alibaba.fastjson.JSONObject params=JSON.parseObject(array.getString(i));
String str=params.getString("dst");
try {
str=URLDecoder.decode(str,"utf-8");
date=str;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return date;
}
public static void main(String[] args) throws UnsupportedEncodingException {
//测试翻译
String msg=EnglishTranslateBaiduUtil.EnglistTranslateChinese("bouygues telecom division mobile ");
System.out.println(msg);
}
}
前端翻译 js info要查询的信息 result拿到的结果
var query=info;
var appid = '20180626000180267';
var key = 'SwHMdwzocdsLMYPJ4M08';
var salt = (new Date).getTime();
var temp;
// 多个query可以用\n连接 如 query='apple\norange\nbanana\npear'
var from = 'auto';
var to = 'zh';
var str1 = appid + query + salt +key;
var sign = MD5(str1);
$.ajax({
url: 'http://api.fanyi.baidu.com/api/trans/vip/translate',
type: 'get',
dataType: 'jsonp',
data: {
q: query,
appid: appid,
salt: salt,
from: from,
to: to,
sign: sign
},
success: function (data) {
result= data.trans_result[0].dst;
}
});
}
//破版。。拿到百度搜索到的标签中的text
/**
* Project Name D3
* File Name GetHtmlContentUtils.java
* Package Name cn.secure.util
* Date 2018年6月26日上午11:06:20
* Copyright (c) 2018, [email protected] All Rights Reserved.
*
*/
package cn.secure.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**@Description TODO
*
* @ClassName GetHtmlContentUtils
* @author
* @date 2018年6月26日 上午11:06:20
* @version V1.0
* @since JDK 1.8
*/
public class GetHtmlContentUtils {
private final static String PreUrl="http://www.baidu.com/s?wd="; //百度搜索URL
private final static String TransResultStartFlag="<span class=\"op_dict_text2\">"; //翻译开始标签
private final static String TransResultEndFlag="</span>"; //翻译结束标签
public static String getTranslateResult(String urlString) throws Exception { //传入要搜索的单词
URL url = new URL(PreUrl+urlString); //生成完整的URL
// 打开URL
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// 得到输入流,即获得了网页的内容
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String preLine="";
String line;
int flag=1;
// 读取输入流的数据,并显示
String content=""; //翻译结果
while ((line = reader.readLine()) != null) { //获取翻译结果的算法
if(preLine.indexOf(TransResultStartFlag)!=-1&&line.indexOf(TransResultEndFlag)==-1){
content+=line.replaceAll(" | ", "")+"\n"; //去电源代码上面的半角以及全角字符
flag=0;
}
if(line.indexOf(TransResultEndFlag)!=-1){
flag=1;
}
if(flag==1){
preLine=line;
}
}
return content;//返回翻译结果
}
public static void main(String[] args) {
String str="fish";
try {
String msg=GetHtmlContentUtils.getTranslateResult(str);
System.out.println(msg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
标签:翻译,java,String,static,params,import,net,百度 From: https://blog.51cto.com/kero99/6674367