【问题标题】:How to make reactive webclient follow 3XX-redirects?如何使响应式 Web 客户端遵循 3XX 重定向?
【发布时间】:2018-05-19 05:48:52
【问题描述】:

我已经创建了一个基本的 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);
    }

}

当我收到 3XX 响应代码时,我希望 Web 客户端使用响应中的位置跟踪重定向并递归调用该 URI,直到我收到非 3XX 响应。

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

【问题讨论】:

标签: spring-boot project-reactor spring-webflux reactor-netty


【解决方案1】:

您需要根据docs配置客户端

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

【讨论】:

  • 谢谢,文档不完整,似乎没有涵盖所有内容。这有助于填补空白!
【解决方案2】:

您可以为函数创建 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);
            }

【讨论】:

  • 这有点像我们最终的结果。似乎 Spring Boot 2.1.0 被延迟了,所以我们将使用这个解决方案一段时间。
猜你喜欢
  • 2016-12-01
  • 2012-11-09
  • 2012-07-27
  • 1970-01-01
  • 2012-07-03
  • 2014-03-13
  • 2018-05-11
  • 2020-10-17
  • 2021-08-24
相关资源
最近更新 更多