Rails Savon 调用 web 服务后,返回结果如何解析

mumu · 2015年10月09日 · 最后由 mumu 回复于 2015年10月13日 · 2318 次阅读
require "savon"

@URL = "http://10.68.2.17/PacsService/PacsService.svc?wsdl"

client = Savon.client(wsdl: @URL)

puts client.operations

response = client.call(:get_patient_info, message: { id:'1' })

puts response

xml_result = response.to_s

puts xml_result

response、xml_result 输出都为

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><GetPatientInfoResponse xmlns="http://tempuri.org/"><GetPatientInfoResult>[{'12':1222},{'34':1234}]</GetPatientInfoResult></GetPatientInfoResponse></s:Body></s:Envelope>

如何获取 GetPatientInfoResult 节点的值

对 Web Service 不熟悉,话说 Web Service 这么 general 的名字被 Java 给带坏了。 如果返回结果不能映射成数值对象的话,那么你只能用解析 xml 字符串的方式处理返回结果了。 在网上搜一下如何用 Nogogiri 去解析 XML 吧。

Savon.client 已经帮你转换成 ruby 对象了 response.body if response.successful?

#2 楼 @ripple 如何取某个节点值呢

#2 楼 @ripple 知道了,是这样 puts response.body[:get_patient_info_response][:get_patient_info_result] ,非常感谢

Web Service 比较不好弄,当时我们对接别人的时候我是用 http client + savon 来配合使用的,如果 post 的 xml 比较复杂的时候还是拼吧

http_resp = Faraday.new.post do |req|
  req.url = 'xxx'
  req.headers = {'Content-Type' => 'text/xml; charset=UTF-8'}
  req.body = "<xml>"
end

httpi_resp = HTTPI::Response.new http_resp.status, http_resp.headers, http_resp.body
globals = {}
globals[:strip_namespaces] = true #这里可以按需求定义很多东西
locals = {}
soap_resp = Savon::Response.new(httpi_resp, globals, locals)

if soap_resp.http.error?
  xxx
end

if soap_resp.soap_fault?
  body_hash = soap_resp.body
  hash = body_hash['Fault']
  fault_code = hash['faultcode']
  fault_msg = hash['faultstring']
end
需要 登录 后方可回复, 如果你还没有账号请 注册新账号