TranslatorUtil.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright 2019-2020 Zheng Jie
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package me.zhengjie.utils;
  17. import cn.hutool.json.JSONArray;
  18. import java.io.BufferedReader;
  19. import java.io.InputStreamReader;
  20. import java.net.HttpURLConnection;
  21. import java.net.URL;
  22. import java.net.URLEncoder;
  23. /**
  24. * @author Zheng Jie
  25. * 翻译工具类
  26. */
  27. public class TranslatorUtil {
  28. public static String translate(String word){
  29. try {
  30. String url = "https://translate.googleapis.com/translate_a/single?" +
  31. "client=gtx&" +
  32. "sl=en" +
  33. "&tl=zh-CN" +
  34. "&dt=t&q=" + URLEncoder.encode(word, "UTF-8");
  35. URL obj = new URL(url);
  36. HttpURLConnection con = (HttpURLConnection) obj.openConnection();
  37. con.setRequestProperty("User-Agent", "Mozilla/5.0");
  38. BufferedReader in = new BufferedReader(
  39. new InputStreamReader(con.getInputStream()));
  40. String inputLine;
  41. StringBuilder response = new StringBuilder();
  42. while ((inputLine = in.readLine()) != null) {
  43. response.append(inputLine);
  44. }
  45. in.close();
  46. return parseResult(response.toString());
  47. }catch (Exception e){
  48. return word;
  49. }
  50. }
  51. private static String parseResult(String inputJson){
  52. JSONArray jsonArray2 = (JSONArray) new JSONArray(inputJson).get(0);
  53. StringBuilder result = new StringBuilder();
  54. for (Object o : jsonArray2) {
  55. result.append(((JSONArray) o).get(0).toString());
  56. }
  57. return result.toString();
  58. }
  59. }