John Doe
John Doe

Reputation: 215

Spring 5 WebClient only making Http call when using .block() after .exchange()

This call works as expected and makes the POST successfully:

public class MyService implements IMyService {

private final WebClient webClient;
private final String url;

MyService(@Qualifier("web-client") WebClient webClient,
                      String url) {
    this.webClient = webClient;
    this.url = url;
}

@SneakyThrows
@Override
public void execute(Long jobId) {
    MultiValueMap<String, String> requestParms = new LinkedMultiValueMap<>();
    requestParms.add("arguments", "--batchJobId=" + jobId.toString());
    HttpEntity<MultiValueMap<String, String>> requestEntity =
        new HttpEntity<>(requestParms, null);

    final WebClient.ResponseSpec responseSpec = webClient.post()
        .uri(new URI(url + "/tasks/executions"))
        .body(BodyInserters.fromMultipartData(requestParms))
        .exchange()
        .block();
}
}

Inside the configuration class:

@Bean
@Qualifier("web-client")
public WebClient getWebClient() {
    return WebClient.builder()
        .filter(basicAuthentication("user", "pass"))
        .filter(printLnFilter())
        .build();
}

private ExchangeFilterFunction printLnFilter() {
    return (request, next) -> {
        System.out.println("\n\n" + request.method().toString().toUpperCase() + ":\n\nURL:"
            + request.url().toString() + ":\n\nHeaders:" + request.headers().toString() + "\n\nAttributes:"
            + request.attributes() + "\n\n");

        return next.exchange(request);
    };
}

In the example above, we see the URL, Attributes, and Headers logged and the Http call success fully made. However, just removing the block() call results in no call ever being made, no logs:

 // No call made
 final WebClient.ResponseSpec responseSpec = webClient.post()
            .uri(new URI(url + "/tasks/executions"))
            .body(BodyInserters.fromMultipartData(requestParms))
            .exchange();

Upvotes: 2

Views: 6546

Answers (1)

Ulises
Ulises

Reputation: 9635

That's because it's non blocking...

From Spring Docs:

Simply put, WebClient is an interface representing the main entry point for performing web requests.

It has been created as a part of the Spring Web Reactive module and will be replacing the classic RestTemplate in these scenarios. The new client is a reactive, non-blocking solution that works over the HTTP/1.1 protocol.

It's an implementation using the Reactive Streams concept through the Project Reactor implementation

Upvotes: 4

Related Questions