3 changed files with 1664 additions and 1390 deletions
@ -0,0 +1,97 @@ |
|||
package com.bx.implatform.util; |
|||
|
|||
import cn.hutool.core.util.RandomUtil; |
|||
import cn.hutool.crypto.digest.DigestUtil; |
|||
import cn.hutool.http.HttpRequest; |
|||
import cn.hutool.http.HttpResponse; |
|||
import cn.hutool.json.JSONObject; |
|||
import cn.hutool.json.JSONUtil; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
|
|||
import java.nio.charset.StandardCharsets; |
|||
import java.util.List; |
|||
|
|||
/** |
|||
* 百度翻译工具类 |
|||
*/ |
|||
@Slf4j |
|||
public class BaiduTranslationUtils { |
|||
|
|||
/** |
|||
* 百度翻译API地址 |
|||
*/ |
|||
private static final String API_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate"; |
|||
|
|||
/** |
|||
* 百度翻译APPID |
|||
*/ |
|||
private static final String APP_ID = "20260420002597860"; |
|||
|
|||
/** |
|||
* 百度翻译密钥 |
|||
*/ |
|||
private static final String SECRET_KEY = "bGdLDbZgM3WMOL09_1qI"; |
|||
|
|||
/** |
|||
* 翻译文本 |
|||
* |
|||
* @param query 待翻译文本 |
|||
* @param from 源语言,可设置为"auto"自动检测 |
|||
* @param to 目标语言 |
|||
* @return 翻译结果 |
|||
*/ |
|||
public static String translate(String query, String from, String to) { |
|||
try { |
|||
// 生成随机数
|
|||
String salt = RandomUtil.randomNumbers(10); |
|||
|
|||
// 生成签名:appid+q+salt+密钥的MD5值
|
|||
String signStr = APP_ID + query + salt + SECRET_KEY; |
|||
String sign = DigestUtil.md5Hex(signStr); |
|||
|
|||
// 发送请求
|
|||
HttpResponse response = HttpRequest.post(API_URL) |
|||
.form("q", query) |
|||
.form("from", from) |
|||
.form("to", to) |
|||
.form("appid", APP_ID) |
|||
.form("salt", salt) |
|||
.form("sign", sign) |
|||
.execute(); |
|||
|
|||
// 解析响应
|
|||
String body = response.body(); |
|||
JSONObject result = JSONUtil.parseObj(body); |
|||
|
|||
// 检查是否有错误
|
|||
if (result.containsKey("error_code")) { |
|||
log.error("百度翻译失败,错误码:{},错误信息:{}", result.getStr("error_code"), result.getStr("error_msg")); |
|||
return result.getStr("error_msg") == null ? "system error" : "system error:" + result.getStr("error_msg"); |
|||
} |
|||
|
|||
// 获取翻译结果
|
|||
List<JSONObject> transResults = result.getBeanList("trans_result", JSONObject.class); |
|||
if (transResults == null || transResults.isEmpty()) { |
|||
log.error("百度翻译结果为空"); |
|||
return "result empty"; |
|||
} |
|||
|
|||
// 返回第一条翻译结果
|
|||
return transResults.get(0).getStr("dst"); |
|||
} catch (Exception e) { |
|||
log.error("百度翻译异常", e); |
|||
return "translation unknown error"; |
|||
} |
|||
} |
|||
|
|||
/** |
|||
* 翻译文本(自动检测源语言) |
|||
* |
|||
* @param query 待翻译文本 |
|||
* @param to 目标语言 |
|||
* @return 翻译结果 |
|||
*/ |
|||
public static String translate(String query, String to) { |
|||
return translate(query, "auto", to); |
|||
} |
|||
} |
|||
File diff suppressed because it is too large
Loading…
Reference in new issue