【问题标题】:How do I post XML to RESTFUL Web Service using Net::HTTP::Post?如何使用 Net::HTTP::Post 将 XML 发布到 RESTFUL Web 服务?
【发布时间】:2009-03-10 10:41:37
【问题描述】:

我无法让它工作,所以任何帮助都将不胜感激!基本上,request.body 包含 Web 服务的有效 XML,如下所示:

<somedata>
<name>Test Name 1</name>
<description>Some data for Unit testing</description>
</somedata>

...但服务返回空 XML。请注意,返回的 id 字段表明它确实命中了数据库,但 name 和 description 字段为 nil:

<somedata>
<id type='integer'>1</id>
<name nil='true'></name>
<description nil='true'></description>
</somedata>

我已经使用 Poster 手动测试了 RESTFUL 服务,它工作正常。

代码如下:

url = URI.parse('http://localhost:3000/someservice/')
request = Net::HTTP::Post.new(url.path)
request.body = "<?xml version='1.0' encoding='UTF-8'?><somedata><name>Test Name 1</name><description>Some data for Unit testing</description></somedata>"
response = Net::HTTP.start(url.host, url.port) {|http| http.request(request)}

#Note this test PASSES!
assert_equal '201 Created', response.get_fields('Status')[0]

有没有人知道为什么 XML 帖子中的数据没有被持久化?

【问题讨论】:

  • 查看服务代码会有所帮助。

标签: ruby-on-rails xml ruby post rest


【解决方案1】:

在对服务一无所知的情况下,这只是一个猜测,但是……服务是否需要 Poster 设置的特定标头而您却没有?

【讨论】:

  • 是的!谢谢,我需要添加以下行并且它有效:request.content_type = 'text/xml'
【解决方案2】:

如果我是你,我会使用 Wiresharktcpflow 或其他一些嗅探器来查看海报和你的应用发送的确切数据,并确保它们是相同的。我见过对最奇怪的东西敏感的服务,比如空格或用户代理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    相关资源
    最近更新 更多