在 Spring 中删除带有 HttpEntity<List> 的 RestTemplate

DELETE in Spring RestTemplate with HttpEntity<List>

我不知道为什么我的代码不起作用,我已经尝试使用 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);

有帮助吗??谢谢!!

从评论中可以清楚地看出您希望它得到 return 400 Bad Request 响应。 RestTemplate 会将这些视为 "client errors" 并且会抛出 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,...)。因此,如果您只希望在请求未成功时对消息进行 returned,您实际上可以执行 Mouad 在评论中提到的操作,并且可以使用 RestTemplatedelete() 方法].