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.
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