How to create Spring WebClient from Apache Http Client
Asked Answered
P

2

7

I want to create WebClient from HttpComponent's org.apache.http.client.HttpClient to use it in async operations.Any idea on how to do it

Parris answered 9/8, 2018 at 11:22 Comment(5)
I don't even have an idea what exactly you're trying to achieve. What did you do so far? Where did run into problems?Guyette
Please, provide more detailsTrembles
Hi Thomas Hi Sergey, I basically have the http client object and need to create a web client object to make async calls as that is what is only supported for reactive programming .Unable to find a way to do thatParris
Spring currently supports Jetty and Netty clients. See How to use Jetty client. Basically any implementation of ClientHttpConnector will work. At this time httpcomponent's implementation is not available - it might be added in future.Ranch
Work on using HttpClient of Java 11 is in progress. See JDK 11 HttpClient integration with WebClient.Ranch
E
10

With the release of Spring Framework 5.3 and Spring Boot 2.4 now there is built-in integration between Apache HttpClient 5.0 and Spring WebClient.

HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom();
clientBuilder.setDefaultRequestConfig(...);
CloseableHttpAsyncClient client = clientBuilder.build();
ClientHttpConnector connector = new HttpComponentsClientHttpConnector(client);

WebClient webClient = WebClient.builder().clientConnector(connector).build();

UPDATE (based on @kolyaiks's comment)

Necessary dependencies:

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.1</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents.core5</groupId>
    <artifactId>httpcore5-reactive</artifactId>
    <version>5.1</version>
</dependency>
Exorable answered 20/9, 2020 at 18:12 Comment(1)
I'd like to mention that you have to add some Maven dependencies to turn this on: httpclient5, httpcore5-parent, httpcore5-reactiveDubbing
B
0

With the org.apache.http.client.HttpClient it's hard cause it was not designed for it you could do it but that would be a quiet scatchy solution with a lot of coding yourself. Better use something designed for like the HttpAsyncClient (also from apache btw.)

Here you find some information and a code example: https://hc.apache.org/httpcomponents-asyncclient-ga/quickstart.html

Good luck

Blunge answered 9/8, 2018 at 11:55 Comment(1)
Can you please share what could be the dirty solution if we dont have the option to use the HttpAsyncClient as we only have the HTTPClient object available whereas we need to use the Spring Webflux based WebClient to make rest calls.Parris

© 2022 - 2024 — McMap. All rights reserved.