如何在 Spring WebClient 中获取上次重定向 URL

How to get last redirect URL in Spring WebClient

可以按如下方式创建遵循重定向的客户端:

WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(
                        HttpClient.create().followRedirect(true)
                ))

在 URL 上调用 HEAD 请求后,如何检索最终的 Location header?换句话说,我们如何才能将最终的 URL 重定向到?

确实HttpClient#followRedirect(true)启用了重定向。 然而,还有 HttpClient#followRedirect(BiPredicate<HttpClientRequest,HttpClientResponse>),在这里您可以更精确地控制何时要重定向,除此之外,您始终可以访问响应和 Location header,所以在任何时候您将知道将重定向到哪个位置。 更多信息 here and here

例如

        WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(
                        HttpClient.create().followRedirect((req, res) -> {
                            System.out.println(res.responseHeaders().get("Location"));
                            return HttpResponseStatus.FOUND.equals(res.status());
                        })
                ))