Java百度翻译API实现中文与印度尼西亚语互相翻译的实践案例
概述
随着全球化的发展和跨国交流的增加,语言的翻译需求也越来越大。百度翻译API是一种强大的工具,可以帮助我们方便快捷地实现不同语言之间的翻译。本文将介绍如何使用Java编程语言通过百度翻译API实现中文与印度尼西亚语之间的互相翻译。
实现步骤
<dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> </dependencies>
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class TranslationAPI { public static void main(String[] args) { String sourceText = "中文文本"; // 需要翻译的中文文本 String appId = "your_app_id"; // 替换为你的APP ID String appKey = "your_app_key"; // 替换为你的APP Key try { String encodedText = URLEncoder.encode(sourceText, "UTF-8"); String urlStr = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=" + encodedText + "&from=zh&to=id&appid=" + appId + "&salt=1435660288&sign=" + generateSign(sourceText, appId, appKey); URL url = new URL(urlStr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } } private static String generateSign(String sourceText, String appId, String appKey) { String sign = appId + sourceText + "1435660288" + appKey; MD5 md5 = new MD5(); return md5.getMD5(sign); } }
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public class TranslationAPI { // ... private static String parseTranslationResult(String response) { JSONObject jsonResult = JSON.parseObject(response); JSONArray translationArray = jsonResult.getJSONArray("trans_result"); StringBuilder translationResult = new StringBuilder(); for (int i = 0; i < translationArray.size(); i++) { JSONObject translationItem = translationArray.getJSONObject(i); String translatedText = translationItem.getString("dst"); translationResult.append(translatedText).append(" "); } return translationResult.toString(); } }
public class TranslationAPI { // ... public static void main(String[] args) { String sourceText = "中文文本"; // 替换为你的中文文本 // ... String translationResult = parseTranslationResult(response.toString()); System.out.println("翻译结果:" + translationResult); } }
以上就是使用Java通过百度翻译API实现中文与印度尼西亚语互相翻译的实践案例。通过这个案例,我们可以掌握如何调用API发送请求,解析API响应并获取翻译结果。希望本文对您学习Java和实现多语言翻译有所帮助!
Atas ialah kandungan terperinci Kes praktikal terjemahan bersama antara Cina dan Indonesia menggunakan Java Baidu Translation API. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!