张世豪
昨天 f0d6cefec73492c29d8323e66fb92ee6bbb60cd2
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package login;
 
import java.io.BufferedReader;
import java.io.InputStream;
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;
 
/**
 * HTTP客户端工具类
 * 提供统一的HTTP请求处理,支持GET和POST请求
 */
public class HttpClientLoca {
    
    private final ApiConfig config;
    
    /**
     * 使用默认配置创建HttpClient
     */
    public HttpClientLoca() {
        this.config = ApiConfig.getDefault();
    }
    
    /**
     * 使用自定义配置创建HttpClient
     */
    public HttpClientLoca(ApiConfig config) {
        this.config = config != null ? config : ApiConfig.getDefault();
    }
    
    /**
     * 发送GET请求
     * 
     * @param url 请求URL
     * @param params URL参数(可选,key-value对)
     * @return ApiResponse 响应结果
     */
    public ApiResponse get(String url, Map<String, String> params) {
        try {
            String fullUrl = buildUrl(url, params);
            HttpURLConnection connection = createConnection(fullUrl, "GET", null);
            
            try {
                int statusCode = connection.getResponseCode();
                String responseBody = readResponse(connection);
                boolean success = statusCode >= 200 && statusCode < 300;
                
                return new ApiResponse(success, statusCode, responseBody, null);
            } finally {
                disconnect(connection);
            }
        } catch (Exception e) {
            return new ApiResponse(false, 500, null, "请求异常: " + e.getMessage());
        }
    }
    
    /**
     * 发送GET请求(无参数)
     */
    public ApiResponse get(String url) {
        return get(url, null);
    }
    
    /**
     * 发送POST请求(JSON格式)
     * 
     * @param url 请求URL
     * @param jsonBody JSON请求体
     * @return ApiResponse 响应结果
     */
    public ApiResponse postJson(String url, String jsonBody) {
        try {
            HttpURLConnection connection = createConnection(url, "POST", jsonBody);
            
            try {
                // 发送JSON数据
                if (jsonBody != null && !jsonBody.isEmpty()) {
                    try (OutputStream outputStream = connection.getOutputStream()) {
                        byte[] jsonBytes = jsonBody.getBytes(StandardCharsets.UTF_8);
                        outputStream.write(jsonBytes);
                        outputStream.flush();
                    }
                }
                
                int statusCode = connection.getResponseCode();
                String responseBody = readResponse(connection);
                boolean success = statusCode >= 200 && statusCode < 300;
                
                return new ApiResponse(success, statusCode, responseBody, null);
            } finally {
                disconnect(connection);
            }
        } catch (Exception e) {
            return new ApiResponse(false, 500, null, "请求异常: " + e.getMessage());
        }
    }
    
    /**
     * 发送POST请求(URL参数,请求体为空)
     * 
     * @param url 请求URL
     * @param params URL参数(可选,key-value对)
     * @return ApiResponse 响应结果
     */
    public ApiResponse post(String url, Map<String, String> params) {
        try {
            String fullUrl = buildUrl(url, params);
            HttpURLConnection connection = createConnection(fullUrl, "POST", null);
            
            try {
                // POST请求即使没有请求体也需要调用getResponseCode来触发请求发送
                int statusCode = connection.getResponseCode();
                String responseBody = readResponse(connection);
                boolean success = statusCode >= 200 && statusCode < 300;
                
                return new ApiResponse(success, statusCode, responseBody, null);
            } finally {
                disconnect(connection);
            }
        } catch (Exception e) {
            return new ApiResponse(false, 500, null, "请求异常: " + e.getMessage());
        }
    }
    
    /**
     * 发送POST请求(无参数,请求体为空)
     */
    public ApiResponse post(String url) {
        return post(url, null);
    }
    
    /**
     * 构建带参数的URL
     */
    private String buildUrl(String baseUrl, Map<String, String> params) throws Exception {
        if (params == null || params.isEmpty()) {
            return baseUrl;
        }
        
        StringBuilder urlBuilder = new StringBuilder(baseUrl);
        boolean first = !baseUrl.contains("?");
        
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first) {
                urlBuilder.append("?");
                first = false;
            } else {
                urlBuilder.append("&");
            }
            
            String key = java.net.URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.name());
            String value = java.net.URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.name());
            urlBuilder.append(key).append("=").append(value);
        }
        
        return urlBuilder.toString();
    }
    
    /**
     * 创建HTTP连接
     */
    private HttpURLConnection createConnection(String urlString, String method, String requestBody) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        // 设置连接属性
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod(method);
        connection.setConnectTimeout(config.getConnectTimeout());
        connection.setReadTimeout(config.getReadTimeout());
        
        // 设置请求头
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("User-Agent", config.getUserAgent());
        
        // POST请求需要设置输出和Content-Type(仅当有请求体时)
        if ("POST".equals(method)) {
            if (requestBody != null && !requestBody.isEmpty()) {
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            } else {
                // POST请求即使没有请求体,也需要设置DoOutput为true
                connection.setDoOutput(true);
            }
        }
        
        return connection;
    }
    
    /**
     * 读取响应内容
     */
    private String readResponse(HttpURLConnection connection) throws Exception {
        int status = connection.getResponseCode();
        InputStream inputStream;
        
        if (status >= 200 && status < 300) {
            inputStream = connection.getInputStream();
        } else {
            inputStream = connection.getErrorStream();
        }
        
        if (inputStream == null) {
            return "";
        }
        
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        
        return response.toString();
    }
    
    /**
     * 安全断开连接
     */
    private void disconnect(HttpURLConnection connection) {
        if (connection != null) {
            try {
                connection.disconnect();
            } catch (Exception e) {
                // 忽略断开连接时的异常
            }
        }
    }
}