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 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
When running Revision 2 (Typed Webclient):