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

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

There is a newer version: 1.0.18
Show newest version
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="tencent")
public final class TencentTranslator
  extends AbstractOnlineTranslator
{
  public TencentTranslator()
  {
    this.langMap.put(LANG.EN, "1");
    this.langMap.put(LANG.ZH, "0");
  }

  @Override
  protected String getResponse(LANG from, LANG targ, String query)
    throws Exception
  {
    Map params = new HashMap<>();
    params.put("sl", (String)this.langMap.get(from));
    params.put("tl", (String)this.langMap.get(targ));
    params.put("st", query);

    return HttpUtil.post("http://fanyi.qq.com/api/translate",params);
  }

  @Override
  protected String parseString(String jsonString)
  {
    StringBuilder str = new StringBuilder();
    JSONObject rootObj = JSONUtil.parseObj(jsonString);
    JSONArray array = rootObj.getJSONArray("result");
    for (int i = 0; i < array.size(); i++) {
      str.append(array.getJSONObject(i).getStr("dst"));
    }
    return str.toString();
  }

  public static void main(String[] args)throws Exception {
    TencentTranslator tencentTranslator = new TencentTranslator();
    String englist = tencentTranslator.getResponse(LANG.EN, LANG.ZH, "englist");
    System.out.println(englist);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy