百度翻译开放平台api调用

首先是文档地址

http://api.fanyi.baidu.com/api/trans/product/apidoc#joinFile

然后配合md5加密类集成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.vshow.control.tool.translate;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

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;

private static final String APP_ID = "";//appid

private static final String SECURITY_KEY = "";//分配的密匙

public TransApi(String appid, String securityKey) {
this.appid = appid;
this.securityKey = securityKey;
}
/**
* @param query 请求翻译的语言
* @param from 请求翻译的语言的语种
* @param to 翻译结果的语种
* @return
*/
public String getTransResult(String query, String from, String to) {
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) {
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;
}

public static String getTransResultEn(String query) {

TransApi api = new TransApi(APP_ID, SECURITY_KEY);

String result = api.getTransResult(query, "auto", "en");

JSONObject jsonObject = JSONObject.fromObject(result);

try {
String resultStr =JSONObject.fromObject(jsonObject.getJSONArray("trans_result").get(0)).get("dst")
+ "";
if(resultStr.equals("Yin")){
resultStr="Cloudy";
}else if(resultStr.equals("yin")){
resultStr="Cloudy";
}
return resultStr;
} catch (Exception e) {
// TODO: handle exception
return "";
}

}

}


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!