百度翻译

来源:互联网 发布:alphago原理讲解 知乎 编辑:程序博客网 时间:2024/06/05 01:15
先到百度翻译申请APPDI和key,具体的地址是:http://api.fanyi.baidu.com/api/trans/product/index  点击申请介入
具体的api在这个地址可以查看:http://api.fanyi.baidu.com/api/trans/product/apidoc
sign=appId+s+"1435660288"+key;(appid和key是到百度翻译api中申请的,200万字符以内免费)md5= md5Encode(sign);source = URLEncoder.encode(s, "UTF-8");String urlBaiDu="http://api.fanyi.baidu.com/api/trans/vip/translate?q="+source+"&from="+_code+"&to=zh&appid="+appId+"&salt=1435660288&sign="+md5;//_code就是原语言的代码(如,中国:zh)result = TestUrl(urlBaiDu);//result就是所需结果

JSONObject resultJson = new JSONObject(result);
JSONArray array = (JSONArray) resultJson.get("trans_result");if (array.length()>0){    JSONObject dst = (JSONObject) array.get(0);    if (dst.has("dst"))    {        finalresult = URLDecoder.decode(dst.getString("dst"), "UTF-8");//这里就是获得的最后结果    }}



//通过url获取结果,此结果是个json字符串

private String TestUrl(String UrlLink){    StringBuffer stringBuffer = new StringBuffer("");    try {        URL postUrl = new URL(UrlLink);        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();        connection.setDoOutput(true);        connection.setDoInput(true);        connection.setReadTimeout(30000);        connection.setConnectTimeout(10000);        connection.setRequestMethod("GET");        connection.setUseCaches(false);        connection.setInstanceFollowRedirects(true);        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));        String str = null;        while ((str = reader.readLine()) != null) {            stringBuffer.append(str);        }        reader.close();    }    catch (Exception e) {        stringBuffer.append("{}");    }    return stringBuffer.toString();}

//字符串转为md5格式

private String md5Encode(String inStr) throws Exception {    MessageDigest md5 = null;    try {        md5 = MessageDigest.getInstance("MD5");    } catch (Exception e) {        System.out.println(e.toString());        e.printStackTrace();        return "";    }    byte[] byteArray = inStr.getBytes("UTF-8");    byte[] md5Bytes = md5.digest(byteArray);    StringBuffer hexValue = new StringBuffer();    for (int i = 0; i < md5Bytes.length; i++) {        int val = ((int) md5Bytes[i]) & 0xff;        if (val < 16) {            hexValue.append("0");        }        hexValue.append(Integer.toHexString(val));    }    System.out.println("baidu"+hexValue.toString());    return hexValue.toString();}

1 0
原创粉丝点击