tags : Spring Boot, Spring WebClient
Spring RestTemplate is a Spring Framework class for making HTTP requests to external services or APIs.
-
HTTP Methods: supports various HTTP methods such as GET, POST, PUT, DELETE, etc.
-
Request and Response Conversion: automatically convert HTTP requests and responses to and from various data formats like JSON, XML, etc., using message converters.
-
Error Handling: It handles HTTP error responses and allows you to define custom error handlers.
-
URI Template Expansion: RestTemplate supports URI template expansion, making it easy to construct dynamic URLs for API endpoints.
-
Basic Authentication: You can easily set up basic authentication for your requests when accessing secured APIs.
-
Request Interceptors: RestTemplate allows you to add request interceptors to modify or inspect outgoing requests before they are sent.
-
Response Extraction: It provides methods to extract data from the HTTP response, making it convenient to process the received data.
RestTemplate restTemplate = new RestTemplate();
String apiUrl = "https://api.example.com/data";
ResponseEntity<String> response = restTemplate.getForEntity(apiUrl, String.class);
if (response.getStatusCode().is2xxSuccessful()) {
String responseBody = response.getBody();
System.out.println(responseBody);
}
RestTemplate Blocking Client vs WebClient Non-Blocking Client
Under the hood, RestTemplate uses the Java Servlet API, which is based on the thread-per-request model.
This means that the thread will block until the web client receives the response. The problem with the blocking code is due to each thread consuming some amount of memory and CPU cycles,
Consequently, the application will create many threads, which will exhaust the thread pool or occupy all the available memory.
Spring WebClient uses an asynchronous, non-blocking solution provided by the Spring Reactive framework.