This question already has an answer here:
Is there a way to get the request body with GET request?
                            
                                (1个答案)
                            
                    
                7个月前关闭。
        

    

我已经实现了一个GetMapping,它带有一个RequestBody并返回一个状态码:

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


我不想用多个RequestParams实现GetMapping,这就是JSON的目的。

现在,我很难测试该Get-Request,因为Jackson无法对ResponseEntity进行反序列化,或者无法读取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);
}


这是杰克逊的例外:

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数据。

10-05 21:20