使用 HttpEntity<List> 在 Spring RestTemplate 中删除

Mig*_*sco 3 spring resttemplate spring-boot spring-rest

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

\n\n

工作正常

\n\n

RestTemplate我可以\xc2\xb4t 得到响应,而\xc2\xb4s 使用相同的端点...。

\n\n
ResponseEntity<String> responseMS  = template.exchange(notificationRestService, HttpMethod.DELETE, new HttpEntity<NotificationRestDTO[]>(arrNotif), String.class);\n
Run Code Online (Sandbox Code Playgroud)\n\n

我尝试ListArray[]

\n\n

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

\n\n
ResponseEntity<String> responseMS = template.exchange(notificationRestService, HttpMethod.PUT, new HttpEntity<NotificationRestDTO>(notificationDTO), String.class);\n
Run Code Online (Sandbox Code Playgroud)\n\n

有什么帮助吗?谢谢!!

\n

g00*_*00b 6

从评论中可以清楚地看出,您希望它返回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();
}
Run Code Online (Sandbox Code Playgroud)

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


ResponseEntity包含您的请求成功执行时的数据(2xx 状态代码,如 200、204...)。因此,如果您只希望在请求不成功时返回一条消息,那么您实际上可以执行 Mouad 在注释中提到的操作,并且可以delete()使用RestTemplate.