百度翻譯開放接口JAVA實現

百度翻譯的開放接口文檔在這裏:http://api.fanyi.baidu.com/api/trans/product/apidocjava

 

至於申請key啥的就不說了,直接進實現。api

我是用HC4.5.1作的,在部分代碼處理上面,會跟3 4 的版本有點不一致。app

	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錯誤的信息。dom

相關文章
相關標籤/搜索