有人可以提供一个如何使用 HTTParty 和 Ruby on Rails 发布 XML 的示例吗? [英] Can someone provide an example for how to post XML using HTTParty and Ruby on Rails?

查看:44
本文介绍了有人可以提供一个如何使用 HTTParty 和 Ruby on Rails 发布 XML 的示例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一些 xml 发布到网络服务,并且我正在尝试使用 HTTParty.有人可以举例说明我如何去做吗?

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?

这是我需要发布的 XML 格式:

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>

这是我目前的课程:

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

我不太确定如何充实 add_candidate.

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

任何帮助将不胜感激.

谢谢.

推荐答案

您有两个选择.HTTParty 允许您发布字符串或哈希值.

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

字符串版本为:

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.

这篇关于有人可以提供一个如何使用 HTTParty 和 Ruby on Rails 发布 XML 的示例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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