spring-bootspring-webclientapache-httpcomponents

Setup WebClient to use HttpComponents


this works (i.e. default WebClient)

WebClient webClient = WebClient.create(url);
Mono<String> mono = webClient.get().exchangeToMono(clientResponse -> {
Mono<String> monos = clientResponse.bodyToMono(String.class);
     return monos;
     });
Mono<ServerResponse> response = ServerResponse.ok().body(mono, String.class);

and when replacing the first line with

HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom();
    CloseableHttpAsyncClient closeableHttpAsyncClient = httpAsyncClientBuilder.build();
    ClientHttpConnector clientHttpConnector = new HttpComponentsClientHttpConnector(closeableHttpAsyncClient);
    WebClient webClient = WebClient.builder().baseUrl(url).clientConnector(clientHttpConnector).build();

to use async HttpComponents. This results in ERR_EMPTY_RESPONSE with the client not sending the request to the server URL. I couldn't find a minimally complete working example of the WebClient using HttpComponents setup. What am I missing here?

The pom info - spring-boot-starter-parent 3.0.1, httpclient5 and httpcore5 5.2


Solution

  • Not sure how did you tests the above code but here is a working test using HttpAsyncClient.

    @Test
    void test() {
        CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.custom().build();
        ClientHttpConnector clientHttpConnector = new HttpComponentsClientHttpConnector(httpAsyncClient);
        WebClient webClient = WebClient.builder()
                .baseUrl("https://google.com")
                .clientConnector(clientHttpConnector)
                .build();
    
        Mono<String> request = webClient.get()
                .uri("/")
                .retrieve()
                .bodyToMono(String.class);
    
        StepVerifier.create(request)
                .assertNext(res -> log.info("response: {}", res))
                .verifyComplete();
    }
    

    Here are dependencies

    'org.springframework.boot' version '3.0.1'

    implementation 'org.springframework.boot:spring-boot-starter-webflux'
    implementation 'org.apache.httpcomponents.client5:httpclient5:5.2'
    implementation 'org.apache.httpcomponents.core5:httpcore5:5.2'
    implementation 'org.apache.httpcomponents.core5:httpcore5-reactive:5.2'
    implementation 'org.apache.httpcomponents.core5:httpcore5-h2:5.2'