官方登录链接:百度翻译开放平台 (baidu.com)
注册教程:百度翻译开放平台 (baidu.com)
创建TranslateUtils工具类
import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.net.URLEncoder; @Component public class TranslateUtils { @Value("${translate.app-id}") private String apiId; //注册账号的APIID(在开发者信息里面找) @Value("${translate.secret-key}") private String secretKey;//注册账号的密钥(在开发者信息里面找) /** * 使用百度翻译 * @param query 要翻译的文本 * @param from 要翻译的文本语言(这里默认使用auto自动识别) * @param to 要翻译的目标语言 * @return */ public String translate(String query,String from,String to) { try { String salt = String.valueOf(System.currentTimeMillis()); String sign = apiId + query + salt + secretKey; // 替换为您的SECRET_KEY //注意这里加密出来的一定要小写,要不然会报54001 String signMd5 = DigestUtils.md5Hex(sign); //拼接url String url = String.format("http://api.fanyi.baidu.com/api/trans/vip/translate?" + "q=%s&from=%s&to=%s&appid=%s&salt=%s&sign=%s", URLEncoder.encode(query, "UTF-8"), from, to, apiId, salt, signMd5); HttpClient client = HttpClients.createDefault(); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); String result = EntityUtils.toString(response.getEntity(), "UTF-8"); //解析返回结果 String trans = TransUtils.getTrans(result); if (trans.equals("20003")){ //返回原来的文本 return query; } return trans; }catch (Exception e){ return query; } } }
创建json解析TransUtils工具类
import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.stereotype.Component; @Component public class TransUtils { public static String getTrans(String result) { try { JSONObject jsonObject = new JSONObject(result); String from = jsonObject.getString("from"); String to = jsonObject.getString("to"); JSONArray transResults = jsonObject.getJSONArray("trans_result"); String src = transResults.getJSONObject(0).getString("src"); String dst = transResults.getJSONObject(0).getString("dst"); return dst; } catch (JSONException e) { //e.printStackTrace(); return "20003"; } } }
接着在对应的模块引用json.jar
标签:JAVA,String,对接,return,query,import,apache,org,百度 From: https://blog.csdn.net/wj520131/article/details/143921313