Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between ResponseEntity and HttpEntity in Spring?

What's the difference between ResponseEntity and HttpEntity in Spring? I want to know the difference between the two and when to use them in a Spring MVC controller.

like image 758
Tim Schwalbe Avatar asked Mar 16 '17 09:03

Tim Schwalbe


3 Answers

HttpEntity can be used to create both RequestEntity and ResponseEntity.

Where as ResponseEntity is subclassed from HttpEntity with a more elaborative way to send the ResponseObject and it only limited to sending the Response. Some Key differences are below :

  1. ResponseEntity inherited from HttpEntity that has an additional HttpStatus Code while Sending the ResponseEntity Object.

  2. Also it has ResponseEntity.BodyBuilder which adds body to the response Object and ResponseEntity.HeadersBuilder which adds header to the Response object.

like image 187
Akash Roy Avatar answered Nov 07 '22 16:11

Akash Roy


An HTTP entity is the majority of an HTTP request or response, consisting of some of the headers and the body, if present. It seems to be the entire request or response without the request or status line (although only certain header fields are considered part of the entity).

while ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.

like image 36
Riasat Mahbub Avatar answered Nov 07 '22 16:11

Riasat Mahbub


HttpEntity wraps both the request and response message. But the ResponseEntity wraps only the response message. ResponseEntity basically inherits from HttpEntity. Response Entity can also have a HTTP status code unlike its parent class. ex:

new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);

like image 4
xpioneer Avatar answered Nov 07 '22 16:11

xpioneer