Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestTemplate: exchange() vs postForEntity() vs execute()

I am working on Rest API using Spring boot and I had to access an application's endpoint. I used RestTemplate for it. I was able to do it using 2 methods,

  • postForEntity():

    responseEntity = 
        restTemplate.postForEntity(uri, httpEntity, ResponseClass.class);
    
  • exchange():

    responseEntity = 
        restTemplate.exchange(uri, HttpMethod.POST, httpEntity, ResponseClass.class);
    

I would like to know the usage and differences of these two methods.

I also see another method execute(). Please shed some light on it. How and when to use it.

like image 254
Praveen Kumar Avatar asked Sep 17 '18 09:09

Praveen Kumar


People also ask

What is RestTemplate Exchange ()?

The exchange method executes the request of any HTTP method and returns ResponseEntity instance. The exchange method can be used for HTTP DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, TRACE methods. Using exchange method we can perform CRUD operation i.e. create, read, update and delete data.

What is the difference between postForObject and postForEntity?

The postForObject() Method The postForObject() works in much the same way postForEntity() does - the only difference is that postForEntity() returns a ResponseEntity , while postForObject() returns that object. To that end, the methods behave the same, other than returning a different type.

What is RestTemplate postForEntity?

The postForEntity method creates new resource by posting the given object to the given URI template using HTTP POST method. The postForEntity method returns instance of ResponseEntity using which we can fetch the information about HTTP status, URI of newly created resource, response content body etc.

What is difference between getForObject and getForEntity?

For example, the method getForObject() will perform a GET and return an object. getForEntity() : executes a GET request and returns an object of ResponseEntity class that contains both the status code and the resource as an object. getForObject() : similar to getForEntity() , but returns the resource directly.


3 Answers

The RestTemplate is a very versatile object.

Let's start with execute, since it's the most generic method:

execute(String url, HttpMethod method, @Nullable RequestCallback requestCallback,         @Nullable ResponseExtractor<T> responseExtractor, Object... uriVariables) 

Note the uriVariables can be passed as a Map too.

execute is designed to be applicable in the highest variety of scenarios possible:

  • The first and second parameters allow any valid combination of URL and method.
  • The request can be modified in a myriad of different ways by passing a custom RequestCallback (a @FunctionalInterface with just one method doWithRequest(ClientHttpRequest request)) before sending it.
  • The response returned from the remote resource can be deserialized in any way necessary by passing a custom ResponseExtractor.

Compare this with exchange:

exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,          Class<T> responseType, Object... uriVariables) 

There are two major differences here:

  • You can now pass an HttpEntity directly, whereas before it needed to be set manually using the RequestCallback.
  • Deserialization mechanics are provided out of the box by passing the desired response type Class.

As you can see, this is much more convenient for everyday use.

Methods like getForEntity and postForEntity are even shorter, easier to understand versions of this:

getForEntity(String url, Class<T> responseType, Object... uriVariables)  postForEntity(String url, @Nullable Object request, Class<T> responseType,               Object... uriVariables) 

Notice postForEntity now allows you to POST any Object directly without a wrapper. There is no performance benefit or detriment to using these instead of execute, as they call execute themselves under the hood - it's simply a matter of convenience.

like image 146
Paul Benn Avatar answered Sep 17 '22 06:09

Paul Benn


RestTemplate is a synchronous client to perform HTTP requests. It offers templates for common scenarios for each HTTP method, in addition to the generalized exchange(...) and execute(...) methods that support less frequent cases.

The Spring Integration documentation summarizes the usage of each method:

postForEntity

Create a new resource via POST and return the representation from the response.

exchange

More generalized, and less opinionated version, of the above methods that provides extra flexibility when needed. It accepts RequestEntity, including HTTP method, URL, headers, and body as input, and returns a ResponseEntity.

These methods allow the use of ParameterizedTypeReference instead of Class to specify a response type with generics.

execute

The most generalized way to perform a request, with full control over request preparation and response extraction via callback interfaces.


In the end, both postForEntity(...), exchange(...) and execute(...) methods will invoke the protected doExecute(...) method, which will perform the actual HTTP request. You can check the source code for details

like image 31
cassiomolin Avatar answered Sep 20 '22 06:09

cassiomolin


Execute(..) The most raw form of method, to make REST call.

Exchange(..) A wrapper over Execute method.

PostForEntity(..) A wrapper method, which further eases the use for making REST calls. You specify the request type in the method name itself(getForEntity, postForEntity), so, need not mention request type in the parameter. The method name in itself becomes self explanatory.

In Exchange & postForEntity, response has to be in Json formats. This Json is further converted to Model class by json-mapper libraries. While, in Execute, we accept response in any format, as we pass the deserializer in Response Executor argument.

like image 25
Aditya Rewari Avatar answered Sep 20 '22 06:09

Aditya Rewari