RestTemplate reduces boilerplate code and enforces RESTful principles.
In this post, we will discuss different ways in which we can use RestTemplate
- HTTP GET call
- HTTP POST call
- HTTP Exchange call
- HTTP DELETE call
Get entry point has two methods
- getForEntity: returns ResponseEntity which can be used to get ResponseStatus code and other parameters.
- getForObject: convert and returns Object passed to it as the parameter. In case RestTemplate is not able to parse will throw RestClientException.
Post entry point has the following methods
- postForObject: convert and returns Object passed to it as the parameter. In case RestTemplate is not able to parse will throw RestClientException.
- postForLocation: returns the Location of that newly created Resource.
- postForEntity: Can be used to submit a Form and return ResponseEntity which can be used to get ResponseStatus code and other parameters
Exchange entry point gives a more generic way of using HTTP calls.
We will see how we can do POST call using exchange method
- Internally the template uses HttpMessageConverter instances to convert HTTP messages to and from POJOs.
- By default, the RestTemplate relies on standard JDK facilities to establish HTTP connections. You can switch to use a different HTTP library.
- Such as Apache HttpComponents, Netty, and OkHttp through the HttpAccessor.setRequestFactory(org.springframework.http.client.ClientHttpRequestFactory) property.
- More detail on Java Doc can be found here.