Skip to content

Spring WebFlux – Why I have to wait for WebClient response?

I have a my WebClient class as per below:

public class WebClientSample {
    public static void main(String[] args) throws InterruptedException {

    public static String mySimpleTestMethod() throws InterruptedException {
        String uri = "http://localhost:8080/some/cool/api/here";
        WebClient webClient = WebClient.create(uri);
        Mono<String> result = webClient
                .headers(headers -> headers.setBasicAuth("admin", "secret"))
        String responseStr = result.subscribe(response -> System.out.println(response)).toString();
        return responseStr;


After execution I get this on my console:

[email protected]

Question: If I comment Thread.sleep(1000); then I dont get any response. Why do I need to wait for the response?


Your code is working with Thread.sleep(1000); because you are blocking the parent thread for some time and within this time you are getting a response back from WebClient.

WebClient is a non-blocking HTTP client. As you need to return the response back from the mySimpleTestMethod method, you need to block until you retrieve the response using Mono#block().

String responseStr = result.block();

and then you can return the response back.

Also, note that in the below code you are calling toString on Disposable type (LambdaMonoSubscriber), LambdaMonoSubscriber doesn’t override toString method, as a result, you are getting string value ([email protected]) from toString method of the Object class.

String responseStr = result.subscribe(response -> System.out.println(response)).toString();