首页 > 解决方案 > Apache http 客户端使用重定向重试

问题描述

我正在使用 apache http 客户端并想下载文件。外部服务具有以下功能:

  1. 要下载文件,我将 GET 请求发送到https://base.url/path/to/file
  2. 这重定向到实际上我可以开始下载文件的 URL。

问题是文件可以定位(复制)在一堆 url 上,并且不能访问所有这些 url(一些主机甚至不解析为 IP)。

我已将重试处理程序设置为我的自定义 http 客户端:

HttpClients.custom()
            .setRetryHandler(new HttpRequestRetryHandler(4))
            .setRedirectStrategy(new LaxRedirectStrategy())
            ...
            .build();
class HttpRequestRetryHandler extends DefaultHttpRequestRetryHandler {
    public HttpRequestRetryHandler(int retryCount) {
        super(retryCount, true, Arrays.asList(InterruptedIOException.class, SSLException.class));
    }

    @Override
    protected boolean handleAsIdempotent(HttpRequest request) {
        String method = request.getRequestLine().getMethod().toUpperCase(Locale.ROOT);
        return "GET".equals(method);
    }
}

但问题是重试仅在重定向之后应用。因此,如果我无法访问重定向的 URL,那么 httpClient 将对其执行 4 个请求(所有这些请求都将失败)。如何对初始 URL 应用重试?

标签: javaapache-httpclient-4.x

解决方案


推荐阅读