【问题标题】:DELETE in Spring RestTemplate with HttpEntity<List>使用 HttpEntity<List> 在 Spring RestTemplate 中删除
【发布时间】:2017-07-18 00:19:13
【问题描述】:

我不知道为什么我的代码不起作用,我已经尝试使用 Postman 并且工作正常:

但是对于RestTemplate,当它使用相同的端点时我无法得到响应...。

ResponseEntity<String> responseMS  = template.exchange(notificationRestService, HttpMethod.DELETE, new HttpEntity<NotificationRestDTO[]>(arrNotif), String.class);

我试过用List 代替Array[]

当我提出PUT 请求时,它工作正常,但只有一个对象:

ResponseEntity<String> responseMS = template.exchange(notificationRestService, HttpMethod.PUT, new HttpEntity<NotificationRestDTO>(notificationDTO), String.class);

有什么帮助吗??谢谢!!

【问题讨论】:

  • 你也应该使用DELETE作为带有resttemplate的http方法吗?
  • 类似:new RestTemplate().delete ( uri, params ).
  • @MouadELFakir restTemplate.exchange() 也应该可以工作。据我所知,delete() API 不允许您发送请求正文。
  • Miguel,你能告诉我们RestTemplate.exchang() 调用的结果是什么吗?它会抛出异常还是其他什么?
  • @g00glen00b 我只从 SoapUI 得到 400 null,在代码中抛出 Spring 类,我什么都看不到

标签: spring spring-boot resttemplate spring-rest


【解决方案1】:

从 cmets 可以清楚地看出,您希望它返回 400 Bad Request 响应。 RestTemplate 会将这些视为“客户端错误”并抛出 HttpClientErrorException

如果你想处理这样的情况,你应该捕获这个异常,例如:

try {
    ResponseEntity<String> responseMS  = template.exchange(notificationRestService, HttpMethod.DELETE, new HttpEntity<NotificationRestDTO[]>(arrNotif), String.class);
} catch (HttpClientErrorException ex) {
    String message = ex.getResponseBodyAsString();
}

在这种情况下(因为您期望String),您可以使用getResponseBodyAsString() 方法。


ResponseEntity 将仅包含您的请求可以成功执行的数据(2xx 状态代码,如 200、204...)。所以,如果你只希望在请求不成功的情况下返回一条消息,你实际上可以做Mouad在cmets中提到的,你可以使用RestTemplatedelete()方法。

【讨论】:

  • 感谢您的回答!正如更新TestRestTemplate.delete(...) 仍然是void ...我不明白为什么没有deleteForEntity 与所有其他HttpMethods 一样,只是response.body = null
  • 其实RestTemplate.patch(...)似乎也是如此
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-27
  • 1970-01-01
  • 2016-08-22
  • 2017-09-14
  • 2016-07-07
  • 2018-04-05
  • 2021-02-02
相关资源
最近更新 更多