restTemplate用body删除
我正在尝试使用请求正文进行DELETE,但我一直收到400(错误的请求)错误。 当我在招摇/邮递员中这样做时,它成功删除了记录。 但是从Java代码我不能这样做
外部API的设计方式需要正文和URL。 它无法改变。 请告诉我如何删除请求正文的条目
public Person delete(Person person, String url, Map uriVariables) throws JsonProcessingException { RestTemplate restTemplate = new RestTemplate(); CustomObjectMapper mapper = new CustomObjectMapper(); HttpEntity requestEntity = new HttpEntity(person); try { ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, Person.class, uriVariables); return responseEntity.getBody(); } catch (RestClientException e) { System.out.println(mapper.writeValueAsString(person)); throw e; } }
当它转到exception时,我将以JSON格式获得JSON请求,并且在Swagger / postman中也能正常工作
我做了一些谷歌搜索,发现当有请求体时,restTemplate有问题删除。 这篇文章没有帮助https://jira.spring.io/browse/SPR-12361有没有办法让它工作
Spring版本4.0.x或更早版本存在问题。
在以后的版本中它已被修复。
这可能是一个迟到的答案,但在我的一个项目中,我通过自定义ClientHttpRequestFactory
解决了这个问题到RestTemplate
如果没有为RestTemplate
提供工厂,它将使用默认实现SimpleClientHttpRequestFactory
在SimpleClientHttpRequestFactory
类中,请求体不允许使用DELETE
方法。
if ("PUT".equals(httpMethod) || "POST".equals(httpMethod) || "PATCH".equals(httpMethod)) { connection.setDoOutput(true); } else { connection.setDoOutput(false); }
只需编写自己的实现
import java.io.IOException; import java.net.HttpURLConnection; import org.springframework.http.client.SimpleClientHttpRequestFactory; public class CustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory { @Override protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { super.prepareConnection(connection, httpMethod); if("DELETE".equals(httpMethod)) { connection.setDoOutput(true); } } }
之后,将RestTemplate
对象创建为
RestTemplate template = new RestTemplate( new CustomClientHttpRequestFactory());
修复了( 4.1.x或更高版本) SimpleClientHttpRequestFactory
类的更高版本
if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod) || "DELETE".equals(httpMethod)) { connection.setDoOutput(true); } else { connection.setDoOutput(false); }
另一种解决方法是使用restTemplate.exchange
,这是一个例子:
try { String jsonPayload = GSON.toJson(request); HttpEntity entity = new HttpEntity (jsonPayload.toString(),headers()); ResponseEntity resp = restTemplate.exchange(url, HttpMethod.DELETE, entity, String.class); } catch (HttpClientErrorException e) { /* Handle error */ }
这个解决方案的好处是你可以将它与所有HttpMethod类型一起使用。