Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

restTemplate.getforobject(),exchange(),entity() .is there any pros and cons for each method?

i have used both entity(),exchange(),getforObject(), and all seems to be working fine . but not sure which is the perfect method for different scenarios.. please give more info about each methods like pros and cons,where to use where not to use.

like image 696
benny Avatar asked Feb 12 '18 07:02

benny


People also ask

What is the use of exchange method in RestTemplate?

Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods. The code given below shows how to create Bean for Rest Template to auto wiring the Rest Template object.

What is RestTemplate getForObject?

The getForObject method fetches the data for the given response type from the given URI or URL template using HTTP GET method. To fetch data for the given key properties from URL template we can pass Object Varargs and Map to getForObject method. The getForObject returns directly the object of given response type.

What are the advantages of using RestTemplate?

RestTemplate class is an implementation of the Template method pattern in the Spring framework. It simplifies the interaction of RESTful Web Services on the client-side. It's right time to invest in Cryptocurrencies Dogecoin !


1 Answers

You can actually go through the docs of RestTemplate to understand the purpose of these methods. There are no pros and cons. Every method serves its own purpose.

getforObject() : Sends an HTTP GET request, returning an object mapped from a response body.

 @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public @ResponseBody Employee employeeById(@PathVariable long id) {
       return employeeRepository.findEmp(id);
    }

if the repository can't find any employee for a given id, then the null response will be sent with status 200(OK). But actually, there was problem. The data was not found. Instead of sending 200(OK), it should have sent 404(Not Found). So, one of the ways, is sending ResponseEntity(that carries more metadata(headers/status codes) related to the response.)

@RequestMapping(value="/{id}", method=RequestMethod.GET)
 public ResponseEntity<Employee> employeeById(@PathVariable long id) {
   Employee employee = employeeRepository.findEmp(id);
   HttpStatus status = HttpStatus.NOT_FOUND;
   if(employee != null ){
     status = HttpStatus.OK; 
   }       
   return new ResponseEntity<Employee>(employee, status);
}

Here, the client will come know the exact status of its request.

exchange : Executes a specified HTTP method against a URL, returning a ResponseEntity containing an object mapped from the response body

like image 145
amdg Avatar answered Dec 23 '22 03:12

amdg