2024.11.8(周五)
用百度api接口实现翻译
package baidu.com; import okhttp3.*; import org.json.JSONObject; import java.io.*; import java.util.Scanner; class Sample { public static final String API_KEY = "hq0yYEvT1ujnn7N0oWY6rrSL"; public static final String SECRET_KEY = "BIKqSqHZqe4D6an2VJeHTgCmaBkhU56J"; static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build(); public static void main(String[] args) throws IOException { // Use Scanner to get input from the user Scanner scanner = new Scanner(System.in); System.out.println("请选择翻译方式:"); System.out.println("1: 英译中"); System.out.println("2: 中译英"); int choice = scanner.nextInt(); scanner.nextLine(); // Consume newline // Set translation direction based on user's choice String fromLang = ""; String toLang = ""; if (choice == 1) { fromLang = "en"; toLang = "zh"; } else if (choice == 2) { fromLang = "zh"; toLang = "en"; } else { System.out.println("Invalid choice. Defaulting to English to Chinese."); fromLang = "en"; toLang = "zh"; } // Ask the user for the text to translate System.out.println("输入内容:"); String textToTranslate = scanner.nextLine(); // Prepare request body MediaType mediaType = MediaType.parse("application/json"); String jsonBody = String.format("{\"from\":\"%s\",\"to\":\"%s\",\"q\":\"%s\"}", fromLang, toLang, textToTranslate); RequestBody body = RequestBody.create(mediaType, jsonBody); // Send translation request Request request = new Request.Builder() .url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + getAccessToken()) .method("POST", body) .addHeader("Content-Type", "application/json") .addHeader("Accept", "application/json") .build(); Response response = HTTP_CLIENT.newCall(request).execute(); // Parse and extract the translated text String responseBody = response.body().string(); JSONObject jsonResponse = new JSONObject(responseBody); String translatedText = jsonResponse .getJSONObject("result") // Get the "result" object .getJSONArray("trans_result") // Get the "trans_result" array .getJSONObject(0) // Get the first element in the array .getString("dst"); // Get the translated text (dst) // Print the translated result System.out.println("翻译结果: " + translatedText); } /** * 从用户的AK,SK生成鉴权签名(Access Token) * * @return 鉴权签名(Access Token) * @throws IOException IO异常 */ static String getAccessToken() throws IOException { MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY); Request request = new Request.Builder() .url("https://aip.baidubce.com/oauth/2.0/token") .method("POST", body) .addHeader("Content-Type", "application/x-www-form-urlencoded") .build(); Response response = HTTP_CLIENT.newCall(request).execute(); return new JSONObject(response.body().string()).getString("access_token"); } }