如何通过 HTTP GET 发送 JSON 并在 return 中获取状态码?

How can I send JSON via HTTP GET and get a status code in return?

我已经实现了一个 GetMapping,它接受一个 RequestBody 和 returns 一个状态代码:

@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);
    }
}

我不想实现具有多个 RequestParam 的 GetMapping,这就是 JSON 的用途。

现在我很难测试 Get-Request,因为 ResponseEntity 要么不能被 Jackson 反序列化,要么 HttpEntity 中的 RequestBody 没有被读取:

@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);
}

这是 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@RequestMapping 注释的特殊版本,充当 @RequestMapping(method = RequestMethod.GET) 的快捷方式。 consumes@RequestMapping(method = RequestMethod.POST)(或专用版本 @PostMapping)有意义,但对 @GetMapping 没有意义。您需要使用 HTTP POST 才能使用您的 JSON 数据。