我打電話給返回XML的REST服務,並使用Jaxb2Marshaller
來編組我的類(例如Foo
,Bar
等)。所以我的客戶端代碼如下所示:如何配置Spring的RestTemplate在返回404 HTTP狀態時返回null
HashMap<String, String> vars = new HashMap<String, String>();
vars.put("id", "123");
String url = "http://example.com/foo/{id}";
Foo foo = restTemplate.getForObject(url, Foo.class, vars);
當服務器端的查找失敗時,它將返回一個404以及一些XML。由於無法讀取XML,我最終得到了一個UnmarshalException
。
Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"exception"). Expected elements are <{}foo>,<{}bar>
響應的主體是:
<exception>
<message>Could not find a Foo for ID 123</message>
</exception>
我如何配置RestTemplate
使RestTemplate.getForObject()
回報null
如果發生了404?
'getForObject',默認情況下應該拋出一個'HttpClientErrorException' 404.你怎麼配置你的'RestTemplate'? – 2017-01-12 21:39:53
@SotiriosDelimanolis我無法再訪問代碼,但是您所描述的默認行爲聽起來像我當時所期待的。 (我應該養成在未來的問題中陳述版本的習慣。) – vegemite4me 2017-01-13 18:00:51