简体   繁体   English

有人可以提供一个如何使用HTTParty和Ruby on Rails发布XML的示例吗?

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

I need to post some xml to a webservice and I'm trying to use HTTParty. 我需要将一些xml发布到web服务,我正在尝试使用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: 以下是我需要发布的XML格式:

<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. 我不太确定如何充实add_candidate。

Any help would be appreciated. 任何帮助,将不胜感激。

Thanks. 谢谢。

You've got two options. 你有两个选择。 HTTParty allows you to post both a string or a hash. HTTParty允许您发布字符串或散列。

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. 如果是这种情况,你可能不得不将身体作为一个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM