|
| 1 | +package com.luoboduner.moo.tool.util; |
| 2 | + |
| 3 | +import cn.hutool.json.JSONArray; |
| 4 | +import org.apache.commons.lang3.StringUtils; |
| 5 | + |
| 6 | +import java.io.BufferedReader; |
| 7 | +import java.io.InputStreamReader; |
| 8 | +import java.net.HttpURLConnection; |
| 9 | +import java.net.URL; |
| 10 | +import java.net.URLEncoder; |
| 11 | +import java.nio.charset.StandardCharsets; |
| 12 | + |
| 13 | +/** |
| 14 | + * 翻译工具类 |
| 15 | + */ |
| 16 | +public class GoogleTranslatorUtil { |
| 17 | + |
| 18 | + /** |
| 19 | + * |
| 20 | + * @param word |
| 21 | + * @param sourceLanguage 源语言 默认auto 英文为 en |
| 22 | + * @param targetLanguage 目标语言 默认zh-CN |
| 23 | + * @return |
| 24 | + */ |
| 25 | + public static String translate(String word,String sourceLanguage,String targetLanguage){ |
| 26 | + try { |
| 27 | + if(StringUtils.isEmpty(sourceLanguage)){ |
| 28 | + sourceLanguage="auto"; |
| 29 | + } |
| 30 | + if(StringUtils.isEmpty(targetLanguage)){ |
| 31 | + targetLanguage="zh-CN"; |
| 32 | + } |
| 33 | + String url = "https://translate.googleapis.com/translate_a/single?" + |
| 34 | + "client=gtx&" + |
| 35 | + "sl=" + sourceLanguage + |
| 36 | + "&tl=" + targetLanguage + |
| 37 | + "&dt=t&q=" + URLEncoder.encode(word, StandardCharsets.UTF_8); |
| 38 | + |
| 39 | + URL obj = new URL(url); |
| 40 | + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); |
| 41 | + con.setRequestProperty("User-Agent", "Mozilla/5.0"); |
| 42 | + |
| 43 | + BufferedReader in = new BufferedReader( |
| 44 | + new InputStreamReader(con.getInputStream())); |
| 45 | + String inputLine; |
| 46 | + StringBuilder response = new StringBuilder(); |
| 47 | + |
| 48 | + while ((inputLine = in.readLine()) != null) { |
| 49 | + response.append(inputLine); |
| 50 | + } |
| 51 | + in.close(); |
| 52 | + return parseResult(response.toString()); |
| 53 | + }catch (Exception e){ |
| 54 | + return word; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + private static String parseResult(String inputJson){ |
| 59 | + JSONArray jsonArray2 = (JSONArray) new JSONArray(inputJson).get(0); |
| 60 | + StringBuilder result = new StringBuilder(); |
| 61 | + for (Object o : jsonArray2) { |
| 62 | + result.append(((JSONArray) o).get(0).toString()); |
| 63 | + } |
| 64 | + return result.toString(); |
| 65 | + } |
| 66 | +} |
0 commit comments