一、图解
通过本文提供的方法得到批量翻译后的藏语json
注意:使用过程中需要联网调用翻译接口
二、上代码
1.导入maven
<!-- 用于解析http请求返回的标签 -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.3</version>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.15</version>
</dependency>
2.方法(直接复制可用)
代码如下(示例):
/**
* 汉语批量翻译
* 方法中扒的http接口 2024.4.9亲测可用
* @param cnJsonObj 需要翻译的汉语json 格式见上部分图解
* @return
*/
public static JSONObject CnToTibetan(JSONObject cnJsonObj){
JSONObject tibetanJsonObj = new JSONObject();
for (String key : cnJsonObj.keySet()) {
String cnValue = cnJsonObj.getString(key);
String resBody = HttpUtils.sendPost("https://nmt.utibet.edu.cn/mt", "src=" + cnValue +"&lang=ct");
Document parse = Jsoup.parse(resBody);
Elements textarea = parse.select("textarea");
String tibetanValue = textarea.get(1).text();
System.out.println("汉语:" + cnValue + ",藏语:" + tibetanValue);
tibetanJsonObj.put(key, tibetanValue);
}
return tibetanJsonObj;
}
3、工具类方法sendPost
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
log.info("sendPost - {}", url);
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("recv - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
总结与用途
在做国际化i18n时可以很好的用到这个方法
方法中用到的翻译接口是我在网上扒的,不能作为正式环境使用