前言
百度翻译开放平台:http://api.fanyi.baidu.com/api/trans/product/index
提交参数
译文语言to这里说是不能设置成auto,但是我测试是可以的。
返回参数
{
"from": "en",
"to": "zh",
"trans_result": [
{
"src": "apple",
"dst": "苹果"
}
]
}
实现
/**
* 翻译
* @param q
* @param from
* @param to
* @return
*/
public static String translate(String q,String from,String to){
String url = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=KEYWORD&from=FROM_NUM&to=TO_NUM&appid=APP_ID&salt=SALT_NUM&sign=SIGN_NUM";
// 签名
String appid = "201602010000107";
// 密钥
String key = "dWYS8bDisLv5_pj_lu";
// 随机数
String salt = String.valueOf(System.currentTimeMillis());
//签名
String sign = appid + q + salt + key; // 加密前的原文
try {
//加密后的签名
String enSign = MD5.md5(sign);
url = url.replace("KEYWORD", URLEncoder.encode(q, "UTF-8")).
replace("APP_ID",appid).
replace("SALT_NUM",salt).
replace("SIGN_NUM",enSign).
replace("FROM_NUM",from).
replace("TO_NUM",to);
System.out.println("url:"+url);
JSONObject jsonObject = doGetStr(url);
JSONArray jsonArray = jsonObject.getJSONArray("trans_result");
StringBuffer dst = new StringBuffer();
for(int i=0;i<jsonArray.size();i++) {
JSONObject jsonObject1 = (JSONObject) jsonArray.get(i);
dst.append(jsonObject1.getString("dst"));
}
return dst.toString();
} catch (Exception e) {
return "翻译出错,请稍候再试";
}
}
controller
if(content.startsWith("翻译")){
String word = content.replaceAll("^翻译", "").trim();
if("".equals(word)){
message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
}else {
message = MessageUtil.initText(toUserName, fromUserName, WeixinUtil.translate(word,"auto","auto"));
}
}
演示
源代码
Weixin.rar
Comments (暂无评论)