Last active
August 28, 2019 19:40
-
-
Save svenakela/d768879b67626c13b532c8f09419bad7 to your computer and use it in GitHub Desktop.
Spring WebClient Wrapper allowing for redirects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
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();
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
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 wrappedWebclient
that takes care of redirects.