0

I am working on a Spring boot project that uses Spring Webclient to do a GET request on a URL which has a 3xx redirection. Using webclient to do the GET request to that url gives 200 response. I would like to stop at the redirection and get a header named "location" from there.

I tried the following code and I am getting a null in response.

WebClient webclient =  WebClient.builder()
        .clientConnector(new ReactorClientHttpConnector(
                HttpClient.create().followRedirect(false)
        )).build();

@GetMapping("/")
Mono<Object> webclientTest2() throws URISyntaxException {
    
    return webclient.get()
            .uri("https://URL_THAT_HAS_REDIRECTION")
            .exchange()
            .flatMap(res -> {

                Headers headers = res.headers();
                System.out.println("Status code: "+res.statusCode());
                headers.asHttpHeaders().forEach((k,v) -> {
                    System.out.println(k+" : "+v);
                });
                return Mono.just(headers.asHttpHeaders().get("location"));
            });                     
}

Webclient isnt stopping at 3xx redirection. The System.out.println statement shows only Status code: 200 and some headers from the next System.out.println statement. How can I get that location header from that 3xx redirection?

Note: One interesting observation I made is using the httpclient instead of webclient is able to retrieve the location header.

HttpClient httpclient = HttpClient.create().followRedirect(false);
justAnotherDev
  • 223
  • 1
  • 6
  • 15
  • 2
    WebClient does not follow redirects by default and definitely shouldn't be when you are explicitly setting it NOT to follow redirects. Can you share the http response you are receiving from the service you are calling? – Michael McFadyen Aug 02 '21 at 21:01
  • **return Mono.just(headers.asHttpHeaders().get("location"));** throws a null pointer exception. Returning Mono.just(headers.asHttpHeaders()) instead is giving me few headers under the status 200 in postman. Optional Note: This concept is a related to **magic links**. I want to do a GET request on a magic link url which would give me a 3xx from which I need *location* header – justAnotherDev Aug 02 '21 at 21:15
  • Have a look in project if you have followRedirect enabled, https://projectreactor.io/docs/netty/release/api/reactor/netty/http/client/HttpClient.html#followRedirect-java.util.function.BiPredicate- i assume you need to disable it – Vova Bilyachat Aug 03 '21 at 00:09
  • @VovaBilyachat Is there anything else I have to do apart from what's there in the code above? I created a HttpClient with followRedirect(false) – justAnotherDev Aug 03 '21 at 01:13
  • One interesting observation I made is using the httpclient instead of webclient is able to retrieve the location header. Check the bottom Note of this post. – justAnotherDev Aug 03 '21 at 15:28

0 Answers0