All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hn.translation.impl.BaiduTranslator Maven / Gradle / Ivy

There is a newer version: 1.0.18
Show newest version
package com.hn.translation.impl;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hn.translation.AbstractOnlineTranslator;
import com.hn.translation.LANG;
import com.hn.translation.annotation.TranslatorComponent;

import java.util.HashMap;
import java.util.Map;

/**
 * 百度翻译
 * https://fanyi-api.baidu.com/
 */
@TranslatorComponent(id = "baidu")
public final class BaiduTranslator
        extends AbstractOnlineTranslator {
    public BaiduTranslator() {
        this.langMap.put(LANG.EN, "en");
        this.langMap.put(LANG.ZH, "zh");
    }

    @Override
    public String getResponse(LANG from, LANG targ, String query) {
        String appId = "20200630000509491";
        String key ="xWzLgCmslzrB31W_hvXc";

        Map param = new HashMap<>(5);
        param.put("from", this.langMap.get(from));
        param.put("to", this.langMap.get(targ));
        param.put("q", query);
        param.put("transtype", "translang");
        param.put("simple_means_flag", "3");
        param.put("appid", appId);
        String salt = RandomUtil.randomString(6);
        param.put("salt",salt);
        // 签名 appid+q+salt+密钥
        String sign = SecureUtil.md5(appId + query + salt + key);
        param.put("sign",sign);
        return HttpUtil.get("http://api.fanyi.baidu.com/api/trans/vip/translate", param);
    }

    @Override
    protected String parseString(String jsonString) {
        if (StrUtil.isBlank(jsonString)) {
            return null;
        }

        JSONObject jsonObject = JSONUtil.parseObj(jsonString);
        JSONArray segments = jsonObject.getJSONArray("trans_result");
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < segments.size(); i++) {
            result.append(i == 0 ? "" : "\n");
            result.append(segments.getJSONObject(i).getStr("dst"));
        }
        return new String(result);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy