gpt4 book ai didi

java - 如何通过 HTTP GET 发送 JSON 并获取返回的状态代码?

转载 作者:行者123 更新时间:2023-12-02 09:24:48 28 4
gpt4 key购买 nike

我实现了一个 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,因为 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 的异常(exception):

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

关于java - 如何通过 HTTP GET 发送 JSON 并获取返回的状态代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58409866/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com