一、注册
api.fanyi.baidu.com/ 登录进行一个注册,自己的
#二、 准备MD5、```
TransApi
import java.io.*; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;
public class MD5 { // 首先初始化一个字符数组,用来存放每个16进制字符 private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/**
* 获得一个字符串的MD5值
*
* @param input 输入的字符串
* @return 输入字符串的MD5值
*
*/
public static String md5(String input) throws UnsupportedEncodingException {
if (input == null)
return null;
try {
// 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”)
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
// 输入的字符串转换成字节数组
byte[] inputByteArray = input.getBytes("utf-8");
// inputByteArray是输入字符串转换得到的字节数组
messageDigest.update(inputByteArray);
// 转换并返回结果,也是字节数组,包含16个元素
byte[] resultByteArray = messageDigest.digest();
// 字符数组转换成字符串返回
return byteArrayToHex(resultByteArray);
} catch (NoSuchAlgorithmException e) {
return null;
}
}
/**
* 获取文件的MD5值
*
* @param file
* @return
*/
public static String md5(File file) {
try {
if (!file.isFile()) {
System.err.println("文件" + file.getAbsolutePath() + "不存在或者不是文件");
return null;
}
FileInputStream in = new FileInputStream(file);
String result = md5(in);
in.close();
return result;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String md5(InputStream in) {
try {
MessageDigest messagedigest = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read = 0;
while ((read = in.read(buffer)) != -1) {
messagedigest.update(buffer, 0, read);
}
in.close();
String result = byteArrayToHex(messagedigest.digest());
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String byteArrayToHex(byte[] byteArray) {
// new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))
char[] resultCharArray = new char[byteArray.length * 2];
// 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去
int index = 0;
for (byte b : byteArray) {
resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
resultCharArray[index++] = hexDigits[b & 0xf];
}
// 字符数组组合成字符串返回
return new String(resultCharArray);
}
}
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder;
import java.io.UnsupportedEncodingException; import java.net.URI; import java.util.HashMap; import java.util.Map;
@Service public class TransApi { private static final String TRANS_API_HOST = "api.fanyi.baidu.com/api/trans/v…";
@Value("${baidu_translate.appid}")
private String appid;
@Value("${baidu_translate.securityKey}")
private String securityKey;
// 添加了一个无参构造器,不然无法注入这个bean,否则需要额外的配置。
public TransApi() {}
@Autowired
private RestTemplate restTemplate;
public TransApi(String appid, String securityKey) {
this.appid = appid;
this.securityKey = securityKey;
}
public String getTransResult(String query, String from, String to) throws UnsupportedEncodingException {
Map<String, String> params = buildParams(query, from, to);
MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
requestParams.setAll(params);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(TRANS_API_HOST);
URI uri = builder.queryParams(requestParams).build().encode().toUri(); // 这里不能进行 encode 了,编码就错误了
System.out.println("uri: " + uri);
return restTemplate.getForObject(uri, String.class);
}
private Map<String, String> buildParams(String query, String from, String to) throws UnsupportedEncodingException {
Map<String, String> params = new HashMap<String, String>();
params.put("q", query);
params.put("from", from);
params.put("to", to);
params.put("appid", appid);
// 随机数
String salt = String.valueOf(System.currentTimeMillis());
params.put("salt", salt);
// 签名
String src = appid + query + salt + securityKey; // 加密前的原文
params.put("sign", MD5.md5(src));
return params;
}
}
# 测试
import com.hmy.testhh.service.TransApi; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;
import java.io.UnsupportedEncodingException;
@RestController @RequestMapping("/translate") public class TranslateController {
@Autowired
private TransApi transApi;
@GetMapping(value = "/query", produces = MediaType.APPLICATION_JSON_VALUE)
public String query(@RequestParam("query") String query,
@RequestParam("from") String from, @RequestParam("to") String to) throws UnsupportedEncodingException {
return transApi.getTransResult(query, from, to);
}
}
