本文目录导读:

我来提供一个Java实现百度翻译接口的完整案例。
百度翻译API配置
首先需要在百度翻译开放平台注册并获取API密钥:
- 官网:https://fanyi-api.baidu.com/
- 获取AppID和密钥
完整实现代码
1 翻译工具类
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
/**
* 百度翻译工具类
*/
public class BaiduTranslateUtil {
// 百度翻译API地址
private static final String TRANSLATE_URL = "http://api.fanyi.baidu.com/api/trans/vip/translate";
// 您的AppID
private static final String APP_ID = "您的AppID";
// 您的密钥
private static final String SECRET_KEY = "您的密钥";
// 随机数
private static final String RANDOM_NUM = String.valueOf(System.currentTimeMillis());
/**
* 翻译方法
* @param query 要翻译的文本
* @param from 源语言(auto表示自动检测)
* @param to 目标语言
* @return 翻译结果
*/
public static String translate(String query, String from, String to) {
try {
Map<String, String> params = buildParams(query, from, to);
String response = httpGet(TRANSLATE_URL, params);
return parseResponse(response);
} catch (Exception e) {
e.printStackTrace();
return "翻译失败: " + e.getMessage();
}
}
/**
* 构建请求参数
*/
private static Map<String, String> buildParams(String query, String from, String to) {
Map<String, String> params = new HashMap<>();
params.put("q", query);
params.put("from", from);
params.put("to", to);
params.put("appid", APP_ID);
params.put("salt", RANDOM_NUM);
// 生成签名
String sign = md5(APP_ID + query + RANDOM_NUM + SECRET_KEY);
params.put("sign", sign);
return params;
}
/**
* GET请求
*/
private static String httpGet(String urlStr, Map<String, String> params) {
try {
StringBuilder urlBuilder = new StringBuilder(urlStr);
urlBuilder.append("?");
for (Map.Entry<String, String> entry : params.entrySet()) {
urlBuilder.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), "UTF-8"))
.append("&");
}
String urlStrFinal = urlBuilder.toString();
URL url = new URL(urlStrFinal);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "UTF-8")
);
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
connection.disconnect();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 解析响应结果
*/
private static String parseResponse(String response) {
if (response == null) {
return "翻译失败";
}
JSONObject jsonObject = JSONObject.parseObject(response);
if (jsonObject.containsKey("error_code")) {
return "错误码: " + jsonObject.getString("error_code") +
", 错误信息: " + jsonObject.getString("error_msg");
}
StringBuilder result = new StringBuilder();
if (jsonObject.containsKey("trans_result")) {
String transResult = jsonObject.getString("trans_result");
JSONObject[] results = JSONObject.parseArray(transResult).toArray(new JSONObject[0]);
for (JSONObject resultObj : results) {
result.append(resultObj.getString("dst"));
}
}
return result.toString();
}
/**
* MD5加密
*/
private static String md5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : digest) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
2 使用示例
public class TranslateDemo {
public static void main(String[] args) {
// 示例1:中文翻译成英文
String text1 = "你好,世界!";
String result1 = BaiduTranslateUtil.translate(text1, "zh", "en");
System.out.println("中文->英文: " + text1 + " = " + result1);
// 示例2:英文翻译成中文
String text2 = "Hello, World!";
String result2 = BaiduTranslateUtil.translate(text2, "en", "zh");
System.out.println("英文->中文: " + text2 + " = " + result2);
// 示例3:自动检测语言
String text3 = "Bonjour le monde";
String result3 = BaiduTranslateUtil.translate(text3, "auto", "zh");
System.out.println("自动检测->中文: " + text3 + " = " + result3);
// 示例4:批量翻译
String[] texts = {"Apple", "Banana", "Orange"};
for (String text : texts) {
String result = BaiduTranslateUtil.translate(text, "en", "zh");
System.out.println(text + " -> " + result);
}
}
}
3 更完整的封装(支持数组批量翻译)
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* 百度翻译封装类(支持批量翻译)
*/
public class BaiduTranslateService {
/**
* 批量翻译
* @param texts 文本数组
* @param from 源语言
* @param to 目标语言
* @return 翻译结果列表
*/
public static List<String> batchTranslate(String[] texts, String from, String to) {
List<String> results = new ArrayList<>();
for (String text : texts) {
String result = BaiduTranslateUtil.translate(text, from, to);
results.add(result);
}
return results;
}
/**
* 翻译并输出详细信息
*/
public static void translateWithDetails(String text, String from, String to) {
// 输出翻译的详细JSON响应
String url = BaiduTranslateUtil.getFullUrl(text, from, to);
System.out.println("请求URL: " + url);
String result = BaiduTranslateUtil.translate(text, from, to);
System.out.println("翻译结果: " + result);
}
}
4 Maven依赖配置
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
使用说明
1 配置步骤
- 访问百度翻译开放平台注册账号
- 创建应用获取AppID和密钥
- 将代码中的
APP_ID和SECRET_KEY替换为实际值
2 支持的语言代码
常用语言代码:
- 中文:
zh - 英文:
en - 日语:
jp - 韩语:
kor - 法语:
fra - 德语:
de - 俄语:
ru - 自动检测:
auto
3 错误码说明
| 错误码 | 说明 |
|---|---|
| 52001 | 请求超时 |
| 52002 | 系统错误 |
| 54001 | 签名错误 |
| 54003 | 访问频率受限 |
| 58001 | 译文语言方向不支持 |
| 54004 | 账户余额不足 |
注意事项
- QPS限制:百度翻译API默认每秒最多请求1次,企业认证后可提高限制
- 字符限制:单次请求最多5000字符
- 费用说明:每月有免费额度,超出后需要付费
- 签名算法:
appid + q + salt + 密钥的MD5值 - 安全建议:不要把AppID和密钥写在前端代码中
运行结果示例
中文->英文: 你好,世界! = Hello, World!
英文->中文: Hello, World! = 你好,世界!
自动检测->中文: Bonjour le monde = 你好世界
Apple -> 苹果
Banana -> 香蕉
Orange -> 橙子
这个案例实现了百度翻译API的完整调用过程,包括签名生成、参数构建、HTTP请求和响应解析等功能,实际使用时,建议将AppID和密钥配置在配置文件中,而不是硬编码在代码里。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播