Skip to content

Instantly share code, notes, and snippets.

@svenakela
Last active August 28, 2019 19:40
Show Gist options
  • Save svenakela/d768879b67626c13b532c8f09419bad7 to your computer and use it in GitHub Desktop.
Save svenakela/d768879b67626c13b532c8f09419bad7 to your computer and use it in GitHub Desktop.
Spring WebClient Wrapper allowing for redirects
package se.cygni.bootcamp.mashup.core;
import java.util.Optional;
import org.springframework.http.HttpHeaders;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
public final class RedirectingWebClient {
private static final int MAX_REDIRECTS = 5;
private final WebClient webClient;
public RedirectingWebClient(final String url) {
webClient = WebClient.create(url);
}
public Mono<ClientResponse> get(final String uri) {
return redirectingRequest(uri, 0);
}
private Mono<ClientResponse> redirectingRequest(final String uri, final int redirects) {
Optional.of(redirects)
.filter(red -> red <= MAX_REDIRECTS)
.orElseThrow(TooManyRedirectsException::new);
return webClient
.get()
.uri(uri)
.exchange()
.flatMap(response -> Optional.of(response)
.filter(r -> r.statusCode().is3xxRedirection())
.map(r -> redirect(r, redirects))
.orElse(Mono.just(response)));
}
private Mono<ClientResponse> redirect(final ClientResponse r, final int redirects) {
String u = r.headers().header(HttpHeaders.LOCATION).get(0);
return redirectingRequest(u, redirects + 1);
}
}
@svenakela
Copy link
Author

Spring 5.0.5 and Spring Boot 2.0.3 relies on a version of Netty that can't handle redirects. Therefore Spring's WebClient can't handle redirects neither. The fix is at the earliest released in the end of 2018 (Spring 5.1) and until we can rely on that version this is a wrapped Webclient that takes care of redirects.

@svenakela
Copy link
Author

svenakela commented Jun 30, 2018

When running Revision 2 (Typed Webclient):

    var wc = new RedirectingWebClient<String>("http://redirect.org", String.class)
                .get("/old")
                .block();
    var dataMappedObject = new RedirectingWebClient<DataMapObject>("http://redirect.org", DataMapObject.class)
                .get("/old")
                .block(); 

@svenakela
Copy link
Author

When running Revision 3 (You handle the typing, not WebClient, and the client can be re-used for different calls):

    var client = new RedirectingWebClient("http://redirect.org");

    var wc = client.get("/whatever/uri/")
                .block()
                .bodyToMono(String.class)
                .block();

    var dataMappedObject = client.get("/another/uri")
                .block()
                .bodyToMono(DataMapObject.class)
                .block();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment