我正在尝试对请求正文进行 DELETE,但我不断收到 400(错误请求)错误。当我在 swagger/postman 中执行此操作时,它成功删除了记录。但从 Java 代码来看我无法做到这一点
外部 API 的设计方式需要 body 和 URL。它无法改变。请让我知道如何删除带有请求正文的条目
public Person delete(Person person, String url, Map<String, String> uriVariables) throws JsonProcessingException {
RestTemplate restTemplate = new RestTemplate();
CustomObjectMapper mapper = new CustomObjectMapper();
HttpEntity<Person> requestEntity = new HttpEntity<Person>(person);
try {
ResponseEntity<Person> responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, Person.class, uriVariables);
return responseEntity.getBody();
} catch (RestClientException e) {
System.out.println(mapper.writeValueAsString(person));
throw e;
}
}
当出现异常时,我将获得 JSON 格式的 JSON 请求,并且在 Swagger/postman 中同样可以正常工作
我做了一些谷歌搜索,发现restTemplate在存在请求正文时存在删除问题。这篇文章没有帮助https://jira.spring.io/browse/SPR-12361有什么办法让它发挥作用吗
解决此问题的另一种方法是使用restTemplate.exchange
,这是一个例子:
try {
String jsonPayload = GSON.toJson(request);
HttpEntity<String> entity = new HttpEntity<String>(jsonPayload.toString(),headers());
ResponseEntity resp = restTemplate.exchange(url, HttpMethod.DELETE, entity, String.class);
} catch (HttpClientErrorException e) {
/* Handle error */
}
这个解决方案的好处是您可以将它与所有 HttpMethod 类型一起使用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)