Hello guys, if you are wondering how to use WebClient on Spring Framework and looking for simple how to examples of WebClient then you have come to the right place. Earlier, I have shared 10 example of RestTemplate in Spring Framework and in this article, I Am going to share 10 example of WebClient in Spring. These examples covers everything from sending GET request to REST API and consuming response, and also sending POST, PUT, and PATCH request to RESTful Web Services. You will also learn how to set header like Basic Authentication and Authorization header, cookies and much more.
But, before we get to the 10 best examples that will teach you everything there is to know about the Spring WebClient in Java, let me tell you a little bit more about what it really is.
10 Examples Of Spring 5 WebClient In Java
Before Spring 5, the RestTemplate had been the main technique used for client-side HTTP accesses. It is part of the Spring MVC project. But these days, WebClient is the most efficient approach.
Before using the WebClient API, you should import the spring-boot-starter-webflux module into your project. You can do this easily:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
In this list, we have compiled 10 examples of the Spring WebClient that will teach you everything you need to know about this innovative approach.
1. Creating And Configuring The WebClient
WebClient webClient1 = WebClient.create();
WebClient webClient2 = WebClient.create("https://client-domain.com");
Additionally, you can also use WebClient.Builder API.
WebClient webClient2 = WebClient.builder()
.baseUrl("http://localhost:3000")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
2. How To Send Requests
WebClient webClient = WebClient.create("http://localhost:3000");
Employee createdEmployee = webClient.post()
.uri("/employees")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.body(Mono.just(empl), Employee.class)
.retrieve()
.bodyToMono(Employee.class);
3. How To Handle Responses
4. WebClient: GET API
Autowired
WebClient webClient;
public Flux<Employee> findAll() {
return webClient.get()
.uri("/employees")
.retrieve()
.bodyToFlux(Employee.class);
}
public Mono<Employee> findById(Integer id)
{
return webClient.get()
.uri("/employees/" + id)
.retrieve()
/*.onStatus(httpStatus -> HttpStatus.NOT_FOUND.equals(httpStatus),
clientResponse -> Mono.empty())*/
.bodyToMono(Employee.class);
}
5. WebClient: POST API
@Autowired
WebClient webClient;
public Mono<Employee> create(Employee empl){
return webClient.post()
.uri("/employees")
.body(Mono.just(empl), Employee.class)
.retrieve()
.bodyToMono(Employee.class);
}
6. WebClient: PUT API
@Autowired
WebClient webClient;
public Mono<Employee> update(Employee e){
return webClient.put()
.uri("/employees/" + e.getId())
.body(Mono.just(e), Employee.class)
.retrieve()
.bodyToMono(Employee.class);
}
7. WebClient: DELETE API
@Autowired
WebClient webClient;
public Mono<Void> delete(Integer id){
return webClient.delete()
.uri("/employees/" +id)
.retrieve()
.bodyToMono(Void.class);
}
8. Understanding Memory Limit
spring.codec.max-in-memory-size=1MB
9. The Connection Timeout
@Bean
public WebClient getWebClient(){
HttpClient httpClient = HttpClient.create()
.tcpConfiguration(client ->
client.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
.doOnConnected(conn -> conn
.addHandlerLast(new ReadTimeoutHandler(10))
.addHandlerLast(new WriteTimeoutHandler(10))));
ClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
return WebClient.builder()
.baseUrl("http://localhost:3000")
.clientConnector(connector)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
}
9. How To Pass The Request Body In WebClient Requests
public Mono<GithubRepo> createGithubRepository(String username, String token,
RepoRequest createRepoRequest) {
return webClient.post()
.uri("/user/repos")
.body(Mono.just(createRepoRequest), RepoRequest.class)
.header("Authorization", "Basic " + Base64Utils
.encodeToString((username + ":" + token).getBytes(UTF_8)))
.retrieve()
.bodyToMono(GithubRepo.class);
}
10. How To Add A Basic Authentication Using A Filter Function
WebClient webClient = WebClient.builder()
.baseUrl(GITHUB_API_BASE_URL)
.defaultHeader(HttpHeaders.CONTENT_TYPE, GITHUB_V3_MIME_TYPE)
.filter(ExchangeFilterFunctions
.basicAuthentication(username, token))
.build();
Spring 5 Web Client Frequently Asked Questions
2. What is the difference between WebClient and RestTemplate?
Before Spring 5, the RestTemplate had been the main technique used for client-side HTTP accesses. It is part of the Spring MVC project. But these days, WebClient is the most efficient approach. Before using the WebClient API, you should import the spring-boot-starter-webflux module into your project. You can do this easily:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
That's all about how to use Spring 5 WebClient in Java. This is one of the most useful class for Java developer as we often need to integrate REST API in our application. If you are familiar with classes like WebClient and RestTemplate then you can confidently take any task which require fetching data from REST API or sending data to REST API.
- Top 5 Spring and Hibernate Training courses
- How to set Accept Header on RestTemplate
- 5 Free Spring Framework and Spring Boot Courses
- 15 Spring Data JPA Interview Questions with Answers
- 30+ Spring MVC Interview Questions for Java Developers
- Top 10 Spring Framework Interview Questions
- 20 REST with Spring Interview Questions for Web developers
- 15 Spring Boot Interview Questions with Answers
- 6 Courses to learn Spring Framework in Depth
- 3 ways to learn Core Spring or Spring MVC better
- How to crack Spring Core Professional 5.0 Certification
- 10 Free Courses to learn Spring Boot for Beginners
- 15 Spring Boot Actuator Interview Questions with Answers
- 15 Microservices Interview Questions with Answers
Thanks for reading this article so far. If you find these essential Spring WebClient examples then please share them with your friends and colleagues on Facebook and Twitter. If you have any questions or feedback then please drop a note.
P. S. - If you are new to Spring Framework and want to learn both Core Spring and Spring MVC from scratch then I highly recommend you join one of these Spring Framework online courses. It covers everything a Java developer needs to know about Spring Framework.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.