HttpEntity<T> is a helper object which encapsulates header and body of an HTTP request or response. It can be used as a handler method parameter.
To get header and body information,the following methods are used:
public HttpHeaders getHeaders()
public T getBody()
The usage of HttpEntity is an alternative to using the two parameter: @RequestHeader HttpHeaders and @RequestBody String/backing type
HttpEntity can be used to return response as well. The additional advantage in this case, when comparing with @ResponseBody is, it can include the headers in the response as well.
Example
In the following example we are going to demonstrate the use of HttpEntity with JUnit tests.
Handling headers and body as String
@RestController
@RequestMapping
public class MyController {
@RequestMapping
public void handleRequest (HttpEntity<String> requestEntity) {
System.out.println("request body: " + requestEntity.getBody());
HttpHeaders headers = requestEntity.getHeaders();
System.out.println("request headers " + headers);
HttpEntity<String> responseEntity = new HttpEntity<String>("my response body");
return responseEntity;
}
}
The unit test
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class ControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup () {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
@Test
public void testUserController () throws Exception {
MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.post("/")
.header("testHeader",
"headerValue")
.content("test body");
this.mockMvc.perform(builder)
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andDo(MockMvcResultHandlers.print());
Output:
request body: test body
request headers {testHeader=[headerValue], Content-Length=[9]}
MockHttpServletRequest:
HTTP Method = POST
Request URI = /
Parameters = {}
Headers = {testHeader=[headerValue]}
Handler:
Type = com.logicbig.example.MyController
Method = public org.springframework.http.HttpEntity<java.lang.String> com.logicbig.example.MyController.handleRequest(org.springframework.http.HttpEntity<java.lang.String>)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[text/plain;charset=ISO-8859-1], Content-Length=[16]}
Content type = text/plain;charset=ISO-8859-1
Body = my response body
Forwarded URL = null
Redirected URL = null
Cookies = []
Using Backing/Command Object
public class User implements Serializable {
private Long id;
private String name;
private String password;
private String emailAddress;
//getters and setters
}
The Controller
@RestController
@RequestMapping
public class MyController {
@RequestMapping("/user")
public HttpEntity<String> handleUserRequest (HttpEntity<User> requestEntity) {
User user = requestEntity.getBody();
System.out.println("request body: " + user);
System.out.println("request headers " + requestEntity.getHeaders());
MultiValueMap<String, String> headers = new HttpHeaders();
headers.put("Cache-Control", Arrays.asList("max-age=3600"));
HttpEntity<String> responseEntity = new HttpEntity<>("my response body", headers);
return responseEntity;
}
}
Unit Test
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class ControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup () {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
@Test
public void testUserController () throws Exception {
MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.post("/user")
.header("testHeader",
"headerValue")
.contentType(MediaType.APPLICATION_JSON)
.content(createUserInJson("joe",
"joe@example.com"));
this.mockMvc.perform(builder)
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andDo(MockMvcResultHandlers.print());
}
private static String createUserInJson (String name, String email) {
return "{ \"name\": \"" + name + "\", " +
"\"emailAddress\":\"" + email + "\"}";
}
}
Output:
request body: User{name='joe', emailAddress='joe@example.com'}
request headers {testHeader=[headerValue], Content-Type=[application/json], Content-Length=[50]}
MockHttpServletRequest:
HTTP Method = POST
Request URI = /user
Parameters = {}
Headers = {testHeader=[headerValue], Content-Type=[application/json]}
Handler:
Type = com.logicbig.example.MyController
Method = public org.springframework.http.HttpEntity<java.lang.String> com.logicbig.example.MyController.handleUserRequest(org.springframework.http.HttpEntity<com.logicbig.example.User>)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Cache-Control=[max-age=3600], Content-Type=[text/plain;charset=ISO-8859-1], Content-Length=[16]}
Content type = text/plain;charset=ISO-8859-1
Body = my response body
Forwarded URL = null
Redirected URL = null
Cookies = []
Example ProjectDependencies and Technologies Used: - Spring Web MVC 4.2.4.RELEASE: Spring Web MVC.
- Spring TestContext Framework 4.2.4.RELEASE: Spring TestContext Framework.
- Java Servlet API 3.0.1
- JUnit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
- jackson-databind 2.7.2: General data-binding functionality for Jackson: works on core streaming API.
- JDK 1.8
- Maven 3.0.4
|