有人能提供一个关于如何使用HTTParty和Ruby on Rails发布XML的例子吗?

时间:2022-10-26 23:17:23

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?

我需要在webservice上发布一些xml,我正在尝试使用HTTParty。有人能给我举个例子吗?

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.

谢谢。

1 个解决方案

#1


16  

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.

现在,我不能确定端点是否需要名称空间,如果需要,哈希版本是否可以工作。如果是这样的话,你可能需要把身体做成绳子。

#1


16  

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.

现在,我不能确定端点是否需要名称空间,如果需要,哈希版本是否可以工作。如果是这样的话,你可能需要把身体做成绳子。