1. 程式人生 > 其它 >百度翻譯引擎的Java示例

百度翻譯引擎的Java示例

技術標籤:百度

百度翻譯引擎的Java示例

package spring;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
 * 百度翻譯引擎java示例程式碼
 */
public class BaiduTranslateDemo{
    
    private static final String UTF8 = "utf-8";
    
    //申請者開發者id,實際使用時請修改成開發者自己的appid
    private static final String appId = "2015063000000001";

    //申請成功後的證書token,實際使用時請修改成開發者自己的token
    private static final String token = "12345678";

    private static final String url = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    //隨機數,用於生成md5值,開發者使用時請啟用下邊第四行程式碼
    private static final Random random = new Random();
    
    public String translate(String q, String from, String to) throws Exception{
        //用於md5加密
        //int salt = random.nextInt(10000);
        //本演示使用指定的隨機數為1435660288
        int salt = 1435660288;
        
        // 對appId+源文+隨機數+token計算md5值
        StringBuilder md5String = new StringBuilder();
        md5String.append(appId).append(q).append(salt).append(token);
        String md5 = DigestUtils.md5Hex(md5String.toString());

        //使用Post方式,組裝引數
        HttpPost httpost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
        nvps.add(new BasicNameValuePair("q", q));  
           nvps.add(new BasicNameValuePair("from", from));  
           nvps.add(new BasicNameValuePair("to", to));  
           nvps.add(new BasicNameValuePair("appid", appId));  
           nvps.add(new BasicNameValuePair("salt", String.valueOf(salt)));  
           nvps.add(new BasicNameValuePair("sign", md5));  
        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));  

        //建立httpclient連結,並執行
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = httpclient.execute(httpost);
        
        //對於返回實體進行解析
        HttpEntity entity = response.getEntity();
        InputStream returnStream = entity.getContent();
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(returnStream, UTF8));
        StringBuilder result = new StringBuilder();
        String str = null;
        while ((str = reader.readLine()) != null) {
            result.append(str).append("\n");
        }
        
        //轉化為json物件,注:Json解析的jar包可選其它
        JSONObject resultJson = new JSONObject(result.toString());

        //開發者自行處理錯誤,本示例失敗返回為null
        try {
            String error_code = resultJson.getString("error_code");
            if (error_code != null) {
                System.out.println("出錯程式碼:" + error_code);
                System.out.println("出錯資訊:" + resultJson.getString("error_msg"));
                return null;
            }
        } catch (Exception e) {}
        
        //獲取返回翻譯結果
        JSONArray array = (JSONArray) resultJson.get("trans_result");
        JSONObject dst = (JSONObject) array.get(0);
        String text = dst.getString("dst");
        text = URLDecoder.decode(text, UTF8);

        return text;
    }
    
    //實際丟擲異常由開發者自己處理
    public static  String translateToEn(String q) throws Exception{
        ApplicationContext container=new FileSystemXmlApplicationContext("src//spring//resource//baidu.xml");
        BaiduTranslateDemo baidu = (BaiduTranslateDemo)container.getBean("baidu");
        
        String result = null;
        try {
            result = baidu.translate(q, "zh", "en");
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return result;
    }
}

轉自https://www.cnblogs.com/codeydt/p/5312063.html