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和實作多語言翻譯有所幫助!
以上是Java百度翻譯API實作中文與印尼文互相翻譯的實作案例的詳細內容。更多資訊請關注PHP中文網其他相關文章!