<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-http</artifactId>
<version>5.7.10</version>
</dependency>
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
public class HttpUtils {
private static final int TIMEOUT = 5000;
private static final int RETRY_COUNT = 3;
public static String doGet(String url) throws HttpException {
HttpRequest request = HttpUtil.createGet(url).timeout(TIMEOUT);
return executeWithRetry(request, RETRY_COUNT);
}
private static String executeWithRetry(HttpRequest request, int retryCount) throws HttpException {
HttpResponse response = null;
for (int i = 0; i <= retryCount; i++) {
try {
response = request.execute();
if (response.isOk()) {
return response.body();
}
} catch (Exception e) {
e.printStackTrace();
}
}
throw new HttpException("请求超时并达到重试次数上限,无法获取到响应!");
}
public static void main(String[] args) {
String result = HttpUtils.doGet("https://api.vvhan.com/api/love?type=json");
System.out.println(result);
}
}