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