com.hn.translation.impl.BaiduTranslator Maven / Gradle / Ivy
package com.hn.translation.impl;
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;
@TranslatorComponent(id="baidu")
public final class BaiduTranslator
extends AbstractOnlineTranslator
{
public BaiduTranslator()
{
this.langMap.put(LANG.EN, "en");
this.langMap.put(LANG.ZH, "zh");
}
public String getResponse(LANG from, LANG targ, String query)
throws Exception
{
Map param = new HashMap<>(5);
param.put("from", this.langMap.get(from));
param.put("to", this.langMap.get(targ));
param.put("query", query);
param.put("transtype", "translang");
param.put("simple_means_flag", "3");
return HttpUtil.get("http://fanyi.baidu.com/v2transapi",param);
}
protected String parseString(String jsonString)
{
JSONObject jsonObject = JSONUtil.parseObj(jsonString);
JSONArray segments = jsonObject.getJSONObject("trans_result").getJSONArray("data");
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