How to get reactive web client to follow 3XX redirects?

I created a basic REST controller that makes requests using the reactive web client in Spring-boot 2 using netty.

@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); } } 

When I get a 3XX response code, I want the web client to redirect using the location in the response and recursively call this URI until I get a 3XX response.

The actual result I get is 3XX answer.

+8
source share
2 answers

You can make the URL parameter of your function and call it recursively while you get 3XX responses. Something like this (in a real implementation, you probably want to limit the number of redirects):

 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); } 
+1
source

You need to configure the client according to the documents

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

Source: https://habr.com/ru/post/1273860/


All Articles