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.
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.
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.
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 !
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With