admin 管理员组文章数量: 1184232
1.翻译代码
/** * 百度翻译类 */
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.*;
import java.util.stream.Collectors;
class BaiduTranslate {
//from输入语言种类
//query需要翻译的语句
//to 目标语言种类
public static String baiduTranslate(String from,String query,String to){
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("from",from);
jsonObject.put("query",query);
jsonObject.put("to",to);
HashMap heads = new HashMap<>();
heads.put("Content-Type", "application/json;charset=UTF-8");
String result = httpPost(jsonObject, "https://fanyi.baidu/ait/text/translate", heads);
String[] state = result.split("event: message");
List<String> translating = Arrays.stream(state).filter(s -> {
return s.contains("翻译中");
}).collect(Collectors.toList());
JSONObject jsonObjectResult = JSONObject.parseObject(translating.get(0).substring(7));
JSONObject data = (JSONObject)jsonObjectResult.get("data");
JSONArray list = (JSONArray)data.get("list");
String dst = "";
for(int i = 0; i < list.size() ; i++){
JSONObject o = (JSONObject)list.get(i);
dst += o.get("dst").toString();
}
return dst;
}catch (Exception e){
return "";
}
}
private static String httpPost(JSONObject param , String url, HashMap heads){
String result = HttpRequest.post(url)
.headerMap(heads, false)
.body(JSONObject.toJSONString(param, true))
.timeout(5 * 60 * 1000)
.execute().body();
return result;
}
}
2.测试类
public class BaiduTranslateTest {
public static void main(String args[]) throws Exception {
System.out.println("-----test-----");
//
String xx = BaiduTranslate.baiduTranslate("zh","你好","kor");
System.out.println(xx);
}
}
3.翻译语言的入参类型参考百度翻译
版权声明:本文标题:使用java调用百度翻译实现翻译功能 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/b/1766010723a3432017.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论