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) {
|
// 忽略断开连接时的异常
|
}
|
}
|
}
|
}
|