百度翻译开放接口JAVA实现
百度翻译的开放接口文档在这里: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错误的信息。