69 lines
2.4 KiB
Java
69 lines
2.4 KiB
Java
package cn.bunny.video.utils;
|
||
|
||
import com.alibaba.fastjson2.JSON;
|
||
import com.alibaba.fastjson2.TypeReference;
|
||
import lombok.extern.slf4j.Slf4j;
|
||
|
||
import java.net.URI;
|
||
import java.net.http.HttpClient;
|
||
import java.net.http.HttpRequest;
|
||
import java.net.http.HttpResponse;
|
||
import java.time.Duration;
|
||
import java.time.temporal.ChronoUnit;
|
||
|
||
@Slf4j
|
||
public class HttpRequestUtils<T> {
|
||
|
||
// 创建 HttpClient 实例并复用
|
||
private static final HttpClient httpClient = HttpClient.newHttpClient();
|
||
|
||
/**
|
||
* 使用GET请求
|
||
*
|
||
* @param url 请求地址
|
||
* @return 返回泛型 T
|
||
*/
|
||
public T requestGET(String url) {
|
||
// 开始时间,用于计算响应时间
|
||
long startTime = System.currentTimeMillis();
|
||
|
||
try {
|
||
HttpRequest request = HttpRequest.newBuilder()
|
||
.uri(URI.create(url))
|
||
.header("Content-Type", "application/json")
|
||
.header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
|
||
.GET()
|
||
.timeout(Duration.of(20, ChronoUnit.SECONDS)) // 请求超时时间
|
||
.build();
|
||
|
||
// 记录请求日志
|
||
log.info("开始请求 URL:{}", url);
|
||
|
||
// 发送请求并获取响应
|
||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||
|
||
// 记录响应时间
|
||
long responseTime = System.currentTimeMillis() - startTime;
|
||
log.info("请求完成,响应时间:{} ms,HTTP 状态码:{}", responseTime, response.statusCode());
|
||
|
||
// 判断响应状态码
|
||
if (response.statusCode() != 200) {
|
||
log.error("请求失败,HTTP 状态码:{}", response.statusCode());
|
||
throw new RuntimeException("请求失败,HTTP 状态码:" + response.statusCode());
|
||
}
|
||
|
||
String body = response.body();
|
||
|
||
// 使用 TypeReference 来解析泛型类型
|
||
TypeReference<T> typeReference = new TypeReference<>() {
|
||
};
|
||
return JSON.parseObject(body, typeReference.getType());
|
||
|
||
} catch (Exception e) {
|
||
// 详细的异常日志记录
|
||
log.error("请求异常,URL:{}", url, e);
|
||
throw new RuntimeException("HTTP 请求失败", e);
|
||
}
|
||
}
|
||
}
|