Add WebClient.filter method

This commit introduces a new method on WebClient: filter, which takes an
filter function, and returns a (filtered) WebClient.

Issue: SPR-14961
This commit is contained in:
Arjen Poutsma 2016-12-06 13:03:49 +01:00
parent 079eca9f63
commit 9e72033036
3 changed files with 47 additions and 1 deletions

View File

@ -95,6 +95,14 @@ class DefaultWebClientBuilder implements WebClient.Builder {
this.strategies));
}
@Override
public WebClient filter(ExchangeFilterFunction filter) {
Assert.notNull(filter, "'filter' must not be null");
ExchangeFilterFunction composedFilter = filter.andThen(this.filter);
return new DefaultWebClient(this.clientHttpConnector, this.strategies, composedFilter);
}
}
private class NoOpFilter implements ExchangeFilterFunction {

View File

@ -50,6 +50,15 @@ public interface WebClient extends ExchangeFunction {
@Override
Mono<ClientResponse> exchange(ClientRequest<?> request);
/**
* Filters this client with the given {@code ExchangeFilterFunction}, resulting in a filtered
* {@code WebClient}.
* @param filterFunction the filter to apply to this client
* @return the filtered client
* @see ExchangeFilterFunction#apply(ExchangeFunction)
*/
WebClient filter(ExchangeFilterFunction filterFunction);
/**
* Create a new instance of {@code WebClient} with the given connector. This method uses

View File

@ -268,7 +268,7 @@ public class WebClientIntegrationTests {
}
@Test
public void filter() throws Exception {
public void buildFilter() throws Exception {
HttpUrl baseUrl = server.url("/greeting?name=Spring");
this.server.enqueue(new MockResponse().setHeader("Content-Type", "text/plain").setBody("Hello Spring!"));
@ -296,6 +296,35 @@ public class WebClientIntegrationTests {
}
@Test
public void filter() throws Exception {
HttpUrl baseUrl = server.url("/greeting?name=Spring");
this.server.enqueue(new MockResponse().setHeader("Content-Type", "text/plain").setBody("Hello Spring!"));
ExchangeFilterFunction filter = (request, next) -> {
ClientRequest<?> filteredRequest = ClientRequest.from(request)
.header("foo", "bar").build();
return next.exchange(filteredRequest);
};
WebClient client = WebClient.create(new ReactorClientHttpConnector());
WebClient filteredClient = client.filter(filter);
ClientRequest<Void> request = ClientRequest.GET(baseUrl.toString()).build();
Mono<String> result = filteredClient.exchange(request)
.then(response -> response.body(toMono(String.class)));
StepVerifier.create(result)
.expectNext("Hello Spring!")
.expectComplete()
.verify();
RecordedRequest recordedRequest = server.takeRequest();
assertEquals(1, server.getRequestCount());
assertEquals("bar", recordedRequest.getHeader("foo"));
}
@After
public void tearDown() throws Exception {
this.server.shutdown();