HttpUtils

 <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; // 重试次数

    /**
     * 发送 GET 请求
     *
     * @param url 请求的URL
     * @return 返回响应内容
     * @throws HttpException 超过重试次数仍然无法获取到响应时抛出异常
     */
    public static String doGet(String url) throws HttpException {
        // 创建 GET 请求,并设置超时时间
        HttpRequest request = HttpUtil.createGet(url).timeout(TIMEOUT);
        // 执行 HTTP 请求并进行重试
        return executeWithRetry(request, RETRY_COUNT);
    }

    /**
     * 执行 HTTP 请求并进行重试
     *
     * @param request    HTTP 请求
     * @param retryCount 重试次数
     * @return 返回响应内容
     * @throws HttpException 超过重试次数仍然无法获取到响应时抛出异常
     */
    private static String executeWithRetry(HttpRequest request, int retryCount) throws HttpException {
        HttpResponse response = null;
        // 重试指定次数
        for (int i = 0; i <= retryCount; i++) {
            try {
                // 执行 HTTP 请求
                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);
    }

}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值