百度翻譯的開放接口文檔在這里:http://api.fanyi.baidu.com/api/trans/product/apidoc
至於申請key啥的就不說了,直接進實現。
我是用HC4.5.1做的,在部分代碼處理上面,會跟3 4 的版本有點不一致。
public static void main(String[] args) {
String query = "搞個乜";
get(query);
post(query);
}
private static void get(String query){
CloseableHttpClient hc = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet();
CloseableHttpResponse response;
try {
String q = URLEncoder.encode(query, "UTF-8");
String from = Lang.AUTO;
String to = Lang.EN;
String salt = RandomStringUtils.randomNumeric(8);
//appid+q+salt+密鑰
String sign = EncryptUtils.md5crypt(TranslateApi.APPID + query + salt + TranslateApi.KEY);
httpGet = new HttpGet(TranslateApi.URL
+ "?q=" + q
+ "&from=" + from
+ "&to=" + to
+ "&appid=" + TranslateApi.APPID
+ "&salt=" + salt
+ "&sign=" + sign);
response = hc.execute(httpGet);
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpGet.releaseConnection();
}
}
private static void post(String query) {
CloseableHttpClient hc = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(TranslateApi.URL);
CloseableHttpResponse response;
try {
String salt = RandomStringUtils.randomNumeric(8);
//appid+q+salt+密鑰
String sign = EncryptUtils.md5crypt(TranslateApi.APPID + query + salt + TranslateApi.KEY);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("q", query));
params.add(new BasicNameValuePair("from", Lang.AUTO));
params.add(new BasicNameValuePair("to", Lang.EN));
params.add(new BasicNameValuePair("appid", TranslateApi.APPID));
params.add(new BasicNameValuePair("salt",salt));
params.add(new BasicNameValuePair("sign", sign));
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
response = hc.execute(httpPost);
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpPost.releaseConnection();
}
}
整個過程其實是比較簡單的,稍微要注意點的,就是POST方法的使用上,由於是使用POST,所以q參數實質上傳遞的就是原值,而不是urlencode后的值。如果傳遞的是編碼之后的值,那么恭喜你了,你想要的結果根本就不是那么一回事。另外一個關鍵點是post參數在加入到POST請求的時候,必須要傳遞UTF-8格式參數過去,否則的話,會報sign錯誤的信息。
