陈昶聿
21 小时以前 5a60b5408414926fd6fe6dbf39c958c749d31779
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package com.ruoyi.common.utils;
 
import okhttp3.*;
 
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.concurrent.TimeUnit;
 
public class OkHttpExample {
    // 定义 JSON 媒体类型
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    // 创建 OkHttpClient 实例(全局单例即可,避免重复创建)
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .readTimeout(5, TimeUnit.SECONDS)
            .build();
 
    public static OkHttpClient createUnsafeOkHttpClient() {
 
        SSLContext sslContext;
        X509TrustManager trustManager = null;
        try {
            // 创建一个信任所有证书的 TrustManager
            TrustManager[] trustAllManagers = new TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) {
                }
 
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) {
                }
 
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }};
 
            // 保存 TrustManager
            trustManager = (X509TrustManager) trustAllManagers[0];
 
            // 初始化 SSLContext
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllManagers, new SecureRandom());
        } catch (Exception e) {
            throw new IllegalStateException("Failed to initialize SSLContext", e);
        }
 
        // 创建 OkHttpClient,设置自定义的 SSLContext
        return new OkHttpClient.Builder().sslSocketFactory(sslContext.getSocketFactory(), trustManager) // 直接使用保存的 TrustManager
                .hostnameVerifier((hostname, session) -> true) // 忽略主机名验证
                .build();
    }
 
 
    public static String sendPostRequest(String url, String jsonBody, String token) throws IOException {
        // 创建 OkHttpClient 实例
        OkHttpClient client = createUnsafeOkHttpClient();
 
        // 创建请求体
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, jsonBody);  // 修改为这种形式
        // 创建请求,设置请求头和请求体
        Request request = new Request.Builder().url(url).addHeader("Authorization", token)// 设置 Token
                .post(body).build();
 
        // 执行请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                return response.body().string(); // 返回响应体
            } else {
                throw new IOException("Unexpected code " + response);
            }
        }
    }
 
    public static String sendGetRequestWithBearerToken(String url, String token) throws IOException {
        // 构建请求:添加 Authorization 请求头(格式:Bearer + 空格 + token)
        Request request = new Request.Builder()
                .url(url)
                .get() // GET 请求(可省略,默认就是 GET)
                .addHeader("Authorization", "Bearer " + token) // 核心:Bearer Token 头
                .addHeader("Content-Type", "application/json") // 按需添加其他头
                .build();
 
        // 执行请求并返回响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败,响应码:" + response.code() + ",消息:" + response.message());
            }
            // 读取响应体(string() 会自动关闭流,无需手动关)
            return response.body().string();
        }
    }
 
    // GET 请求方法
    public static String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .get() // 默认为 GET,可省略
                .build();
 
        // 执行请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("GET 请求失败:" + response);
            }
            return response.body().string(); // 读取响应体
        }
    }
 
    // POST 请求方法(携带 JSON 参数)
    public static String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
 
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("POST 请求失败:" + response);
            }
            return response.body().string();
        }
    }
 
    // POST 请求方法(form-urlencoded + 忽略SSL证书,适用于OAuth2 token端点)
    public static String postFormUnsafe(String url, Map<String, String> formParams) throws IOException {
        OkHttpClient unsafeClient = createUnsafeOkHttpClient();
 
        FormBody.Builder formBuilder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : formParams.entrySet()) {
            formBuilder.add(entry.getKey(), entry.getValue());
        }
 
        Request request = new Request.Builder()
                .url(url)
                .post(formBuilder.build())
                .build();
 
        try (Response response = unsafeClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("POST form 请求失败:" + response.code() + " " + response.message());
            }
            return response.body().string();
        }
    }
 
    // GET 请求方法(参数拼接到URL + 忽略SSL证书,适用于OAuth2 token端点)
    public static String getUnsafe(String url, String token) throws IOException {
        OkHttpClient unsafeClient = createUnsafeOkHttpClient();
 
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token) // 核心:Bearer Token 头
                .get()
                .build();
 
        try (Response response = unsafeClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("GET form 请求失败:" + response.code() + " " + response.message());
            }
            return response.body().string();
        }
    }
 
}