ResponseEntity<T> vs HttpEntity<T>
Understand which one is better to use for spring developers.
1. Introduction:
In a world of development handling HTTP Requests and Responses are important and every spring developers should know how to handle these requests and responses. To handle this Request and Response we are having 3 important classes in spring.
HttpEntity<T>
RequestEntity<T>
ResponseEntity<T>
In this blog, we are mainly focusing on HttpEntity
vs ResponseEntity
in the Spring framework.
ResponseEntity<T>
and HttpEntity<T>
both class belongs to org.springframework.http
package in spring framework.
HttpEntity<T>
is the base class of ResponseEntity<T>
.
HttpEntity<T>
represents Request and Response entities while ResponseEntity<T>
only represents the Response entity.
HttpEntity<T>
represents an HTTP Request or Response entity, consisting of headers
and body
.
ResponseEntity<T>
represents a complete HTTP Response. ResponseEntity<T>
represents the body
, headers
, status code
in HTTP Response. With the help of ResponseEntity<T>
, we can fully configure HTTP Response.
ResponseEntity<T>
& HttpEntity<T>
are generic type. That means we can use any type of response body.
Here is an example of HttpEntity<T>
and ResponseEntity<T>
:
2. Where to use HttpEntity & ResponseEntity:
You can use both of them as return type with
RestTemplate
.Example of
HttpEntity
withRestTemplate
:Example of
ResponseEntity
withRestTemplate
:
You can use
HttpEntity
andResponseEntity
in Controller:Example of
HttpEntity
can be used as Request parameter and Return type:ResponseEntity
as return type in Controller:
3. Which one is Better :
With the help of HttpEntity<T>
We can access request and response headers and body but we don't have control over the status code. But with the help of ResponseEntity<T>
We can get headers, body and status codes and we can customize them as per need.
So the ResponseEntity
is more better than HttpEntity
as it provides extra feature to set status code of Response object.
4. What to learn Next :
You can learn more about HttpEntity
and ResponseEntity
. I have provided link for the same. After completing this you can learn about RequestEntity
in Spring framework.