Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Spring WebClient without Spring Boot

I have a very limited need to be able to make HTTP request. I see WebClient is the new replacement for RestTemplate. But it seems it is impossible to use WebClient, without dragging in the whole of spring boot; which is not what I want to do. Any way to use WebClient without Spring boot?

like image 316
Finlay Weber Avatar asked Sep 04 '20 11:09

Finlay Weber


People also ask

Should I use WebClient instead of RestTemplate?

Even on the official Spring documentation, they advise to use WebClient instead. WebClient can basically do what RestTemplate does, making synchronous blocking calls. But it also has asynchronous capabilities, which makes it interesting. It has a functional way of programming, which makes it easy to read as well.

How do I call a Rest service using WebClient?

If you have Spring WebFlux on your classpath, you can also choose to use WebClient to call remote REST services. Compared to RestTemplate , this client has a more functional feel and is fully reactive. You can create your own client instance with the builder, WebClient.

What can I use instead of RestTemplate?

WebClient is part of Spring WebFlux and is intended to replace the classic RestTemplate. Compared to RestTemplate , WebClient has a more functional feel and is fully reactive. Since Spring 5.0, RestTemplate is deprecated.


1 Answers

You can make asynchronous HTTP request using Reactor Netty HttpClient (docs). Spring WebClient uses it under the hood. Just add dependency

<dependency>
    <groupId>io.projectreactor.netty</groupId>
    <artifactId>reactor-netty</artifactId>
    <version>0.9.11.RELEASE</version>
</dependency>

and make request

HttpClient.create()
            .request(HttpMethod.GET)
            .uri("http://example.com/")
            .responseContent()
            .asString()
            .subscribe(System.out::println);
like image 149
mikhail.sharashin Avatar answered Sep 22 '22 05:09

mikhail.sharashin