无关风月
2024-12-09 2053b8fe0e98d4b4449bc756a93ced78f42277c4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.jilongda.optometry.utils.dingding;
 
import com.alibaba.fastjson.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 "";
    }
 
 
}