如何使反应式webclient遵循3XX重定向?

Mar*_*und 8 spring-boot project-reactor reactor-netty spring-webflux

我创建了一个基本的REST控制器,它使用netty在Spring-boot 2中使用被动Webclient进行请求.

@RestController
@RequestMapping("/test")
@Log4j2
public class TestController {

    private WebClient client;

    @PostConstruct
    public void setup() {

        client = WebClient.builder()
                .baseUrl("http://www.google.com/")
                .exchangeStrategies(ExchangeStrategies.withDefaults())
                .build();
    }


    @GetMapping
    public Mono<String> hello() throws URISyntaxException {
        return client.get().retrieve().bodyToMono(String.class);
    }

}
Run Code Online (Sandbox Code Playgroud)

当我收到3XX响应代码时,我希望webclient使用响应中的Location来跟踪重定向,并递归调用该URI,直到我得到非3XX响应.

我得到的实际结果是3XX响应.

Ada*_*ord 10

您需要根据文档配置客户端

           WebClient.builder()
                    .clientConnector(new ReactorClientHttpConnector(
                            HttpClient.create().followRedirect(true)
                    ))
Run Code Online (Sandbox Code Playgroud)


And*_*vić 7

您可以创建函数的 URL 参数,并在获得 3XX 响应时递归调用它。像这样(在实际实现中,您可能希望限制重定向的数量):

public Mono<String> hello(String uri) throws URISyntaxException {
    return client.get()
            .uri(uri)
            .exchange()
            .flatMap(response -> {
                if (response.statusCode().is3xxRedirection()) {
                    String redirectUrl = response.headers().header("Location").get(0);
                    return response.bodyToMono(Void.class).then(hello(redirectUrl));
                }
                return response.bodyToMono(String.class);
            }
Run Code Online (Sandbox Code Playgroud)