resttemplate返回类型,如何将RestTemplate与多种响应类型一起使用?

I'm using spring RestTemplate for communication with a xml webservice backend as follows:

ResponseEntity dto = restTemplate.postForObject(url, postData, MainDTO.class);

Problem: the backend might either respond with MainDTO for normal data or with ErrorDTO in case of failures. But both with HTTP 200.

But I don't know which object will come back before! Anyways restTemplate requires me to pass the class type before.

So, how could I parse the xml either to normal or the error bean?

Sidenote: I don't have any control of the webservice backend.

解决方案

As you would figure, the problem is that the backend should return you errors with HTTP error codes, that's what they are there for.

But as you said, you don't have control over the backend so what you can do is first get it as a String

ResponseEntity dto = restTemplate.postForObject(url, postData, String.class);

Then you can attempt to parse the string response as a MainDTO with either Jackson or Gson (whatever you have in your project, which you should, because I believe Spring's RestTemplate uses either on of them internally) with a try/catch and if it fails, then you try with to parse it with your ErrorDto.

Update

Oh, I just read that it was an XML service, not a JSON on, the approach above is still valid, but instead of using Jackson or Gson, you can use SimpleXML (http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#deserialize) which allows you to deserialize XML in an "easy" way, you just need to annotate your models with their annotations which are described in their tutorials and examples.

This Spring's example (http://spring.io/guides/gs/consuming-rest-xml-android/) might also provide an insight in how to use SimpleXML.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值