Can someone provide an example for how to post XML using HTTParty and Ruby on Rails?

好久不见. 提交于 2019-12-12 08:45:28

问题


I need to post some xml to a webservice and I'm trying to use HTTParty. Can someone provide an example as to how I go about doing so?

Here is the format of the XML I need to post:

<Candidate xmlns="com.mysite/2010/10/10" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<FirstName></FirstName>
<LastName></LastName>
<Email></Email>
<Gender></Gender>
</Candidate>

Here is my class so far:

require 'httparty'


class Webservice
  include HTTParty
  format :xml
  base_uri 'mysite.com'
  default_params :authorization => 'xxxxxxx'

  def self.add_candidate(first_name,last_name,email,gender)
    post('/test.xml', :body => "")    
  end  
end

I'm not quite sure how to flesh out add_candidate.

Any help would be appreciated.

Thanks.


回答1:


You've got two options. HTTParty allows you to post both a string or a hash.

The string version would be:

post('/test.xml', :body => "<Candidate xmlns=\"com.mysite/2010/10/10\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><FirstName>#{first_name}</FirstName><LastName>#{last_name}</LastName><Email>#{email}</Email><Gender>#{gender}</Gender></Candidate>")

Functional, but not pretty. I'd do this instead:

post('/test.xml', :body => {
  :Candidate => {
    :FirstName => first_name,
    :LastName  => last_name,
    :Email     => email,
    :Gender    => gender,
  }
}

Now, I can't say for sure whether the namespaces are required by the endpoint, and if so, whether the hash version will work. If that's the case, you may have to go with doing the body as a string.



来源:https://stackoverflow.com/questions/3773939/can-someone-provide-an-example-for-how-to-post-xml-using-httparty-and-ruby-on-ra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!