[英]How to get the response body (JSON) in Java from an HTTP delete method when called using the REST template
這是我的第一個問題,我是使用REST模板和Spring的初學者,如果我問的是簡單問題,我深表歉意。
我正在嘗試使用REST模板從另一個組件調用delete方法。 我在POSTMAN中收到的響應是以下JSON:
{
"code": 100,
"message": "my message"
}
我不應該刪除該對象,因此我的請求失敗,並出現org.springframework.web.client.HttpClientErrorException。
在日志中,我看到的是:
[Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 400 Bad Request] with root cause...
我進行了一些搜索,發現嘗試用restTemplate調用rest服務時,如果返回400,則響應主體丟失。
這是我用來捕獲HttpClientErrorException的代碼:
try{
restTemplate.delete(url);
}
catch (HttpClientErrorException e) {
LOG.error("FM HttpClientErrorException caught");
LOG.error("FM response body : {}", e.getResponseBodyAsString());
LOG.error("FM response headers message: {}", e.getResponseHeaders().toString());
LOG.error("FM response message : {}", e.getMessage());
LOG.error("FM response status : {}", e.getStatusCode());
}
我在其他帶有HttpEntity <List>的Spring RestTemplate中的DELETE中看到,一種解決方案是捕獲異常並嘗試獲取響應的主體。
但是,就我而言,這始終是空的。
我嘗試過使用restTemplate中的交換來獲取響應,然后捕獲上述異常,但是我的身體仍然是空的:
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.DELETE, null, String.class);
LOG.info("FM response body : {}", response.getBody());
LOG.info("FM response status : {}", response.getStatusCode());
單元測試結果:
Unit tes2018-06-12T15:23:02,960Z [main] ERROR c.v.b.s.impl.ServiceImpl - HttpClientErrorException caught
2018-06-12T15:23:02,960Z [main] ERROR c.v.b.s.impl.ServiceImpl - response body : []
2018-06-12T15:23:02,960Z [main] ERROR c.v.b.s.impl.ServiceImpl - response headers message: {}
2018-06-12T15:23:02,960Z [main] ERROR c.v.b.s.impl.ServiceImpl - response message : 400 Bad Request
2018-06-12T15:23:02,960Z [main] ERROR c.v.b.s.impl.ServiceImpl - response status : 400t results:
問題是:
我也看到了這篇文章: REST中成功的DELETE語句的HTTP狀態返回代碼是什么? 第三個問題是:
非常感謝您,有關代碼或解決方案的任何幫助或建議都將受到贊賞。
1,2)是的,有可能。 根據我自己的經驗,我比起Spring來更喜歡使用JAX-RS規范附帶的REST Client。 https://docs.oracle.com/javaee/7/api/javax/ws/rs/client/package-summary.html
您可以提出自己喜歡的任何請求,然后獲取正文,而與結果代碼無關。 什么都不會丟失。
我知道這不能完全回答您的第一個問題,但可能會有所幫助。
3)最佳做法是返回表示不同原因的不同錯誤代碼。 訪問是否被拒絕? 資源不可用嗎? 是否存在意外錯誤?
然后,您可以使用Swagger / OpenApi / etc輕松記錄所有這些信息。
這些都應該足以處理潛在的異常。 如果這還不夠,您可能需要創建支持方法來驗證可以刪除資源(例如:GET / api / users / {id} / isDeletable)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.