Java调用有道翻译 - 对国家名称由英文翻译为中文

这个接口为免费的

  @Autowired
  SmsCountryService countryService;

  @Test
  public void updateZhName(){
    // 有道翻译接口
    String url = "http://fanyi.youdao.com/openapi.do?keyfrom=xinlei&key=759115437&type=data&doctype=json&version=1.1&q=";
    // 查询出所有的英文国家名字
    List<SmsCountry> countries = countryService.queryAllName();
    // httpclient
    CloseableHttpClient client = HttpClientBuilder.create().build();
    // 翻译每个国家的名字,并且更新数据库
    for (SmsCountry country:countries) {
      HttpGet request = new HttpGet(url + URLEncoder.encode(country.getName()));
      try {
        CloseableHttpResponse response = client.execute(request);
        String str = EntityUtils.toString(response.getEntity(), "utf-8");
        JSONObject jsonObject = JSON.parseObject(str);
        // 取出json字符串中数组的值
        String s = (String) jsonObject.getJSONArray("translation").get(0);
        System.out.println(">>>>> " + s);
        if (!StringUtil.isEmpty(s)){
        SmsCountry smsCountry = new SmsCountry();
        smsCountry.setId(country.getId());
        smsCountry.setNameZh(s);
        countryService.updateNameById(smsCountry);
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容