wzp
2025-05-09 ef6a2fb3b547190f35b3baf99280eaead42b4f57
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package com.ruoyi.common.utils;
 
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;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
import com.alibaba.fastjson.JSON;
 
/**
 * HTTP工具类
 */
public class HttpUtil {
    
    private static final int CONNECT_TIMEOUT = 60000;
    private static final int READ_TIMEOUT = 60000;
    
    static {
        try {
            // 创建信任所有证书的TrustManager
            TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }
                }
            };
            
            // 初始化SSLContext
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            
            // 设置主机名验证器
            HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
        } catch (Exception e) {
            throw new RuntimeException("初始化SSL上下文失败", e);
        }
    }
    
    /**
     * 发送POST请求
     * @param url 请求URL
     * @param params 请求参数
     * @return 响应内容
     */
    public static String post(String url, Map<String, String> params) {
        StringBuilder response = new StringBuilder();
        HttpURLConnection conn = null;
        try {
            // 创建连接
            URL requestUrl = new URL(url);
            boolean isHttps = url.toLowerCase().startsWith("https");
            
            // 根据协议类型创建连接
            if (isHttps) {
                conn = (HttpsURLConnection) requestUrl.openConnection();
            } else {
                conn = (HttpURLConnection) requestUrl.openConnection();
            }
            
            // 设置请求属性
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            
            // 设置超时时间
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(READ_TIMEOUT);
            
            // 构建JSON参数字符串
            String jsonParams = JSON.toJSONString(params);
            
            // 发送请求参数
            try (OutputStream os = conn.getOutputStream()) {
                os.write(jsonParams.getBytes(StandardCharsets.UTF_8));
                os.flush();
            }
            
            // 获取响应码
            int responseCode = conn.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("HTTP请求失败,响应码: " + responseCode);
            }
            
            // 读取响应
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            }
            
        } catch (Exception e) {
            throw new RuntimeException("HTTP请求失败: " + e.getMessage(), e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        
        return response.toString();
    }
 
    /**
     * 发送GET请求
     * @param url 请求URL
     * @param params 请求参数
     * @return 响应内容
     */
    public static String get(String url, Map<String, String> params) {
        StringBuilder response = new StringBuilder();
        HttpURLConnection conn = null;
        try {
            // 构建带参数的URL
            StringBuilder urlBuilder = new StringBuilder(url);
            if (params != null && !params.isEmpty()) {
                urlBuilder.append("?");
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    urlBuilder.append(entry.getKey())
                            .append("=")
                            .append(entry.getValue())
                            .append("&");
                }
                urlBuilder.deleteCharAt(urlBuilder.length() - 1); // 删除最后一个&
            }
            
            // 创建连接
            URL requestUrl = new URL(urlBuilder.toString());
            boolean isHttps = url.toLowerCase().startsWith("https");
            
            // 根据协议类型创建连接
            if (isHttps) {
                conn = (HttpsURLConnection) requestUrl.openConnection();
            } else {
                conn = (HttpURLConnection) requestUrl.openConnection();
            }
            
            // 设置请求属性
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Accept", "application/json");
            
            // 设置超时时间
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(READ_TIMEOUT);
            
            // 获取响应码
            int responseCode = conn.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("HTTP请求失败,响应码: " + responseCode);
            }
            
            // 读取响应
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            }
            
        } catch (Exception e) {
            throw new RuntimeException("HTTP请求失败: " + e.getMessage(), e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        
        return response.toString();
    }