tags : Spring Boot, Spring RestTemplate URL : howtodoinjava.com

Spring WebClient is a non-blocking and reactive web client to perform HTTP requests. The WebClient has been added in  Spring 5  and provides the fluent functional-style API for sending HTTP requests and handling the responses.

Before Spring 5, RestTemplate has been the primary technique for client-side HTTP accesses, which is part of the Spring MVC project. In Spring 5 and Spring 6, using _WebClient_ is the recommended approach.

To use WebClient api, we must have spring-boot-starter-webflux module imported into the project.


pom.xml

<dependency>     
	<groupId>org.springframework.boot</groupId>     
	<artifactId>spring-boot-starter-webflux</artifactId> 
</dependency>

1. Creating a Spring WebClient Instance

To create _WebClient_ bean, we can follow any one of the given approaches.

1.1. Using WebClient.create()

The create() method is an overloaded method and can optionally accept a base URL for requests.

WebClient webClient1 = WebClient.create();  //with empty URI
WebClient webClient2 = WebClient.create("https://client-domain.com");

1.2. Using WebClient.Builder API

We can also build the client using the DefaultWebClientBuilder class, which uses builder pattern style fluent-API.

WebClient webClient2 = WebClient.builder()
        .baseUrl("http://localhost:3000")
        .defaultCookie("cookie-name", "cookie-value")
        .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
        .build();