如何将RestTemplate与多种响应类型一起使用? [英] How to use RestTemplate with multiple response types?

查看:520
本文介绍了如何将RestTemplate与多种响应类型一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用spring RestTemplate xml webservice后端进行通信,如下所示:

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

问题:后端可能以 MainDTO 对于普通数据,或者在出现故障时使用 ErrorDTO 。但是两者都是 HTTP 200



但我不知道之前会回来哪个对象!无论如何 restTemplate 要求我之前传递类型。



<那么,我怎么能将xml解析为普通或错误bean?



旁注:我对webservice后端没有任何控制权。

解决方案

正如您所想,问题是后端应该使用HTTP错误代码返回错误,这是他们在那里。



但正如你所说,你无法控制后端,所以你能做的就是先把它作为一个字符串

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

然后你可以尝试将字符串响应解析为 MainDTO 使用Jackson或Gson(无论你在项目中有什么,你应该,因为我相信Spring的RestTemplate在内部使用它们)和try / catch,如果它失败了,那么你试着用它来解析它使用 ErrorDto



更新



哦,我刚看到这是一个 XML 服务,而不是 JSON on,这个方法以上仍然有效,但不是使用 Jackson Gson ,您可以使用 SimpleXML http://simple.sourceforge。 net / download / stream / doc / tutorial / tutorial.php #deserialize )允许您以简单的方式反序列化XML,您只需要使用他们的教程s 和示例



这个Spring的例子( http://spring.io/guides/gs/consuming-rest-xml-android/ )也可能提供如何使用的见解 SimpleXML


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

ResponseEntity<MainDTO> 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<String> 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.

这篇关于如何将RestTemplate与多种响应类型一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆