问题描述
我不知道为什么我的代码不起作用,我试过 Postman 并且工作正常:
I don't know why my code is not working, I've tried with Postman and works fine:
但是对于 RestTemplate
,当它使用相同的端点时,我无法得到响应.......
But with RestTemplate
I can´t get a response while it´s using the same endpoint... .
ResponseEntity<String> responseMS = template.exchange(notificationRestService, HttpMethod.DELETE, new HttpEntity<NotificationRestDTO[]>(arrNotif), String.class);
我试过用 List
代替 Array[]
当我发出一个 PUT
请求时,它工作正常,但只有一个对象:
When i made a PUT
request it´s works fine but with one object:
ResponseEntity<String> responseMS = template.exchange(notificationRestService, HttpMethod.PUT, new HttpEntity<NotificationRestDTO>(notificationDTO), String.class);
有什么帮助吗??谢谢!!
Any help?? Thanks!!
推荐答案
从评论中可以明显看出您期望它返回 400 Bad Request 响应.RestTemplate
会将这些视为客户端错误",并且会抛出一个 HttpClientErrorException
.
From the comments it became clear that you're expecting it to return a 400 Bad Request response. RestTemplate
will see these as "client errors" and it will throw a HttpClientErrorException
.
如果你想处理这样的情况,你应该捕获这个异常,例如:
If you want to handle cases like this, you should catch this exception, for example:
try {
ResponseEntity<String> responseMS = template.exchange(notificationRestService, HttpMethod.DELETE, new HttpEntity<NotificationRestDTO[]>(arrNotif), String.class);
} catch (HttpClientErrorException ex) {
String message = ex.getResponseBodyAsString();
}
在这种情况下(因为您需要 String
),您可以使用 getResponseBodyAsString()
方法.
In this case (since you expect a String
), you can use the getResponseBodyAsString()
method.
ResponseEntity
将只包含在您的请求可以成功执行的情况下的数据(2xx 状态代码,如 200、204、...).所以,如果你只希望在请求不成功时返回一条消息,你实际上可以做评论中提到的 Mouad,你可以使用 RestTemplate 的
delete()
方法代码>.
The ResponseEntity
will only contain the data in case your request can be executed successfully (2xx status code, like 200, 204, ...). So, if you only expect a message to be returned if the request was not successfully, you can actually do what Mouad mentioned in the comments and you can use the delete()
method of the RestTemplate
.
这篇关于使用 HttpEntity<List> 在 Spring RestTemplate 中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!