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

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

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


import cn.hutool.core.util.StrUtil;
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="youdao")
public final class YoudaoTranslator
  extends AbstractOnlineTranslator
{
  public YoudaoTranslator()
  {
    this.langMap.put(LANG.EN, "EN");
    this.langMap.put(LANG.ZH, "ZH_CN");
  }

  @Override
  protected String getResponse(LANG from, LANG targ, String query)
    throws Exception
  {
    Map params = new HashMap<>();
    params.put("type", "data");
    params.put("q", query);
    params.put("doctype", "json");
    params.put("version", "1.1");
    params.put("keyfrom", "Skykai521");
    params.put("key", "977124034");

    return HttpUtil.get("http://fanyi.youdao.com/openapi.do",params);
  }

  @Override
  protected String parseString(String jsonString)
  {
    StringBuilder result = new StringBuilder();
    JSONObject jsonObject = JSONUtil.parseObj(jsonString);
    String translation = jsonObject.getStr("translation");
    if(StrUtil.isNotBlank(translation)){
      result.append(translation.replace("[\"","")
              .replace("\"]",""));
    }

    return new String(result);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy