package com.jilongda.applet.utils.dingding; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.core.JsonParser; import com.google.gson.JsonObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; public class DingTalkAccessTokenRequest { public static String getAccessTokenRequest() throws Exception { // 定义URL URL url = new URL("https://api.dingtalk.com/v1.0/oauth2/accessToken"); // 打开连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Host", "api.dingtalk.com"); connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); connection.setDoOutput(true); // 设置允许输出 // 准备请求体 String requestBody = "{\"appKey\":\"ding9xnitayotphtuaxa\",\"appSecret\":\"8I88pUQgJyteYsGscECS-RAIkc-vh2HlJwDzX5dhIFkI4Avpo5D_dmXBQM9flVzC\"}"; // 发送请求 try (OutputStream outputStream = connection.getOutputStream()) { outputStream.write(requestBody.getBytes(StandardCharsets.UTF_8)); } // 获取响应码,假设我们需要检查是否成功 int responseCode = connection.getResponseCode(); connection.getResponseMessage(); System.out.println("Response Code : " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { // 如果状态码为200 try (BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } // 打印或处理响应数据 System.out.println("Response Data: " + response.toString()); JSONObject jsonObject = JSONObject.parseObject(response.toString()); String o = (String) jsonObject.get("accessToken"); return o; } } else { System.err.println("Failed with HTTP error code : " + responseCode); } // 如果需要读取响应体,可以使用以下代码: // BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); // String inputLine; // StringBuffer response = new StringBuffer(); // while ((inputLine = in.readLine()) != null) { // response.append(inputLine); // } // in.close(); // 这里我们没有处理响应体,实际应用中需要根据API的响应结构来解析JSON并处理结果 return ""; } }