案例背景,按照官方给的Demo,实在是太啰嗦了,
大致步骤
封装数据>签名>发送请求,
仔细一看劈里啪啦一大堆,最后还要手动关流关连接,难道整合到SpringBoot项目里面我还得为内存管理考虑
所以就有了如下需求
使用
RestTemplate的对象进行发送请求数据,RestTemplate由springboot自行管理
java
package com.example.demo2.baidu2;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
public class Trans {
private static final String APP_ID = "自己的APPID";
private static final String SECURITY_KEY = "自己的密钥";
private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";
public static void main(String[] args) throws UnsupportedEncodingException {
String query = "高度600米";
Map<String, String> params = new HashMap<String, String>();
params.put("q", query);
params.put("from", "auto");
params.put("to", "en");
params.put("appid", APP_ID);
// 随机数
String salt = String.valueOf(System.currentTimeMillis());
params.put("salt", salt);
// 签名
String src = APP_ID + query + salt + SECURITY_KEY; // 加密前的原文
String md5 = getMD5(src);
md5= md5.toLowerCase();
params.put("sign", md5);
String s = get(TRANS_API_HOST, params);
System.out.println(s);
}
public static String get(String host, Map<String, String> params2) throws UnsupportedEncodingException {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
String s = params2.get("q");
String salt = params2.get("salt");
String appid = params2.get("appid");
String to = params2.get("to");
String from = params2.get("from");
String sign = params2.get("sign");
// String encode = URLEncoder.encode(s, "UTF-8");
params.add("salt",salt);
params.add("appid",appid);
params.add("to",to);
params.add("from",from);
params.add("q",s);
params.add("sign",sign);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(host, HttpMethod.POST, requestEntity, String.class);
int statusCode = response.getStatusCodeValue();
if (statusCode != 200) {
System.out.println("Http错误码:" + statusCode);
}
return response.getBody();
}
public static String getMD5(String s) {
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
try {
byte[] btInput = s.getBytes(StandardCharsets.UTF_8);
MessageDigest mdInst = MessageDigest.getInstance("MD5");
mdInst.update(btInput);
byte[] md = mdInst.digest();
int j = md.length;
char[] str = new char[j * 2];
int k = 0;
for (byte byte0 : md) {
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}