我打电话给返回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