Master Spring 6.1 RestClient: Simple HTTP Calls, Error Handling, and Advanced Exchange

This article introduces Spring 6.1’s new synchronous RestClient, showing how to perform basic GET and POST requests, convert responses to objects, handle errors with onStatus, and use the advanced exchange method for custom request‑response processing, positioning RestClient as a modern replacement for RestTemplate.

Programmer DD
Programmer DD
Programmer DD
Master Spring 6.1 RestClient: Simple HTTP Calls, Error Handling, and Advanced Exchange

In the recently released Spring 6.1 M2, a new synchronous HTTP client called RestClient was introduced. It offers a fluent API similar to WebClient while serving as a modern replacement for the long‑standing RestTemplate.

RestClient Examples

HTTP Request

A simple GET request returning a string demonstrates the API, which resembles WebClient and is less cumbersome than RestTemplate:

RestClient restClient = RestClient.create();

String result = restClient.get()
  .uri("https://example.com")
  .retrieve()
  .body(String.class);
System.out.println(result);

For richer responses, toEntity can return a ResponseEntity with status, headers and body:

ResponseEntity<String> result = restClient.get()
  .uri("https://example.com")
  .retrieve()
  .toEntity(String.class);

System.out.println("Response status: " + result.getStatusCode());
System.out.println("Response headers: " + result.getHeaders());
System.out.println("Contents: " + result.getBody());

RestClient also supports automatic conversion of JSON responses to domain objects, e.g. converting to a Pet instance:

int id = ...;
Pet pet = restClient.get()
  .uri("https://petclinic.example.com/pets/{id}", id)
  .accept(APPLICATION_JSON)
  .retrieve()
  .body(Pet.class);

A POST request with a JSON body can be written as:

Pet pet = ...;
ResponseEntity<Void> response = restClient.post()
  .uri("https://petclinic.example.com/pets/new")
  .contentType(APPLICATION_JSON)
  .body(pet)
  .retrieve()
  .toBodilessEntity();

Error Handling

By default RestClient throws a RestClientException subclass for 4xx and 5xx responses. You can override this behavior with onStatus:

String result = restClient.get()
  .uri("https://example.com/this-url-does-not-exist")
  .retrieve()
  .onStatus(HttpStatusCode::is4xxClientError,
    (request, response) -> {
      throw new MyCustomRuntimeException(response.getStatusCode(),
        response.getHeaders());
    })
  .body(String.class);

Advanced Handling with exchange

The exchange method provides a flexible entry point for custom request‑response processing. It gives access to both request and response objects, allowing you to implement complex logic when the simple methods are insufficient:

Pet result = restClient.get()
  .uri("https://petclinic.example.com/pets/{id}", id)
  .accept(APPLICATION_JSON)
  .exchange((request, response) -> {
    if (response.getStatusCode().is4xxClientError()) {
      throw new MyCustomRuntimeException(response.getStatusCode(),
        response.getHeaders());
    } else {
      Pet pet = convertResponse(response);
      return pet;
    }
  });

Conclusion

While many developers are familiar with RestTemplate, its usage has declined in favor of newer clients. Spring 6.1’s RestClient fills the gap with a concise, fluent API that complements WebClient and offers a modern alternative to RestTemplate.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentspringHTTPRestClient
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.