I've implemented a GetMapping that takes a RequestBody and returns a status code:
@GetMapping(consumes = "application/json", produces = "application/json")
public ResponseEntity getAgreement(@RequestBody DataObject payload) {
Boolean found = agreementService.findSingleAgreement(payload);
if (found) {
return new ResponseEntity(HttpStatus.OK);
} else {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
}
I do not want to implement a GetMapping with multiple RequestParams, that's what the JSON's for.
Now I'm having a hard time testing that Get-Request because ResponseEntity either can't be deserialized by Jackson or the RequestBody in HttpEntity is not being read:
@Test
public void testGetRequest() {
DataObject dataObject = new DataObject();
dataObject.setAgrType("A"); // more setters exist
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<DataObject> entity = new HttpEntity<>(dataObject, headers);
ResponseEntity<DataObject> answer = this.restTemplate
.withBasicAuth(username, password)
.exchange(URL, HttpMethod.GET, entity,
new ParameterizedTypeReference<ResponseEntity>() {}); // exhange's causing trouble!!
assertThat(answer.getStatusCode()).isEqualTo(HttpStatus.OK);
}
Here's the Exception from Jackson:
org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.springframework.http.ResponseEntity]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.http.ResponseEntity` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator) at [Source: (PushbackInputStream); line: 1, column: 2]
@GetMapping
is a specialized version of @RequestMapping
annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET)
. consumes
makes sense for @RequestMapping(method = RequestMethod.POST)
(or for the specialized version, @PostMapping
) but not for @GetMapping
. You need to use HTTP POST to be able to consume your JSON data.