spring - 使用 Spring WebClient 重试时添加新 header

标签 spring spring-boot request-headers spring-retry spring-webclient

webclientbuilder.baseUrl(url)
                .defaultHeaders(headers -> headers.addAll(requestHeader))
                .build()
                .post()
                .uri("/uri")
                .bodyValue(data)
                .exchange()
                .flatMap(response  -> {
                                if(response.statusCode() == HttpStatus.UNAUTHORIZED){
                                                //retry with updated token in header
                                }
                })
                //return bodyToMono of specific object when retry is done or if
                //response status is 2xx

如有任何关于如何处理此问题的建议,我们将不胜感激!正如评论所说,如果 statusCode 为 UNAUTHORIZED,并且如果 statusCode 为 2xx,则在重试发布请求之前,我需要将新 token 添加到 header 中,然后返回 bodyToMono。

最佳答案

您可以通过向网络客户端添加过滤器来解决此问题:

public ExchangeFilterFunction retryOn401() {
    return (request, next) -> next.exchange(request)
            .flatMap((Function<ClientResponse, Mono<ClientResponse>>) clientResponse -> {
                if (clientResponse.statusCode() == HttpStatus.UNAUTHORIZED) {
                    return authClient.getUpdatedToken() //here you get a Mono with a new & valid token
                            .map(token -> ClientRequest
                                    .from(request)
                                    .headers(headers -> headers.replace("Authorization", Collections.singletonList("Bearer " + token)))
                                    .build())
                            .flatMap(next::exchange);
                } else {
                    return Mono.just(clientResponse);
                }
            });
}

因此,当 webclient 重试未经授权的请求时,它可以获得一个新的 token 并在执行重试之前将其设置在 header 中。 确保将其添加到网络客户端:

webclientbuilder.baseUrl(url)
            .defaultHeaders(headers -> headers.addAll(requestHeader))
            .filter(retryOn401())
            .build();

关于spring - 使用 Spring WebClient 重试时添加新 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60496128/

相关文章:

java - 使用 derby 通过 EmbeddedDatabaseBuilder 重新执行应用程序后,表正在刷新

java - Gradle , Kotlin : How to add another spring boot project as a module dependency in intellij

jpa - Spring Boot 2 - H2 数据库 - @SpringBootTest - org.h2.jdbc.JdbcSQLException : Table already exists 失败

java - 声明类型不能为 null

java - Maven/Spring : AopNamespaceUtils NoSuchMethod Error

java - 从 WebListener 中的 ServerContainer 中删除端点

java - 设置请求 header 并转发到另一个应用程序

spring - 如何访问 Spring MVC REST Controller 中的 HTTP header 信息?

javascript - 如何在 Angular 中执行带有请求 header 的 ajax post

spring - 在类路径资源...中定义的bean 'hibernateSearchService' 无法注册