今天继续了昨天未完成的软件案例分析大作业
import okhttp3.*; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.util.Scanner; class Sample { public static final String API_KEY = "h1Hn3oHAWMObDjjFGUY9a2sP"; public static final String SECRET_KEY = "B0cVpGwGb08h8fqochevBsgOFGi6G4oA"; static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build(); public static void main(String[] args) throws IOException { // 获取用户输入的要翻译的文本 Scanner scanner = new Scanner(System.in); System.out.print("请输入要翻译的文本:"); String textToTranslate = scanner.nextLine(); // 获取用户选择的目标语言 String targetLanguage = getUserTargetLanguage(); // 构建请求体的 JSON 对象 JSONObject requestBodyJson = new JSONObject(); requestBodyJson.put("from", "auto"); // 源语言自动检测 requestBodyJson.put("to", targetLanguage); // 目标语言根据用户选择 requestBodyJson.put("q", textToTranslate); // 添加要翻译的文本 // 创建请求体 MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, requestBodyJson.toString()); // 创建HTTP请求 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(); // 解析翻译结果 String translatedText = parseTranslationResult(response.body().string()); System.out.println("翻译结果:" + translatedText); } /** * 解析翻译结果 * * @param responseBody 响应体字符串 * @return 翻译结果 */ static String parseTranslationResult(String responseBody) { JSONObject responseJson = new JSONObject(responseBody); JSONArray transResultArray = responseJson.getJSONObject("result").getJSONArray("trans_result"); // 假设只翻译一段文本,取第一个翻译结果 if (transResultArray.length() > 0) { return transResultArray.getJSONObject(0).getString("dst"); } else { return "未能获取翻译结果"; } } /** * 从用户的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); // 创建HTTP请求 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(); // 发起请求并获取响应,解析JSON获取Access Token Response response = HTTP_CLIENT.newCall(request).execute(); return new JSONObject(response.body().string()).getString("access_token"); } /** * 获取用户选择的目标语言 * * @return 目标语言代码 */ static String getUserTargetLanguage() { Scanner scanner = new Scanner(System.in); System.out.print("请选择目标语言(输入 'zh' 翻译为中文,输入 'en' 翻译为英文):"); return scanner.nextLine(); } }
标签:总结,body,翻译,return,String,每日,static,12.12,new From: https://www.cnblogs.com/louwangshayu/p/17897996.html