Ruby-on-rails 如何使用 Net::HTTP::Post 将 XML 发布到 RESTFUL Web 服务?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/629632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I post XML to RESTFUL Web Service using Net::HTTP::Post?
提问by Darren Jensen
I am having trouble getting this to work so any help would be appreciated! Basically, the request.body contains valid XML for the Web Service like so:
我无法让它工作,所以任何帮助将不胜感激!基本上, request.body 包含 Web 服务的有效 XML,如下所示:
<somedata>
<name>Test Name 1</name>
<description>Some data for Unit testing</description>
</somedata>
...but the service returns empty XML. Note that the id field is returned suggesting that it does actually hit the database, but the name and description fields are nil:
...但服务返回空的 XML。请注意,返回的 id 字段表明它确实访问了数据库,但 name 和 description 字段为零:
<somedata>
<id type='integer'>1</id>
<name nil='true'></name>
<description nil='true'></description>
</somedata>
I have manually tested the RESTFUL service using Poster and it works fine.
我已经使用海报手动测试了 RESTFUL 服务,它工作正常。
Here is the code:
这是代码:
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]
Does anyone have any clues why the data in the XML post is not persisted?
有没有人知道为什么 XML 帖子中的数据没有持久化?
采纳答案by Hank Gay
Without knowing anything about the service, this is just a guess, but… is the service expecting a specific header that Poster is setting and you aren't?
在对服务一无所知的情况下,这只是一个猜测,但是……该服务是否需要海报正在设置的特定标头而您没有?
回答by vasi
If I were you, I'd use Wireshark, tcpflowor some other sniffer to look at the exact data Poster and your app are sending, and make sure they're identical. I've seen services that were sensitive to the weirdest things, like whitespace or user agent.
如果我是你,我会使用Wireshark、tcpflow或其他一些嗅探器来查看 Poster 和您的应用发送的确切数据,并确保它们是相同的。我见过对最奇怪的东西敏感的服务,比如空格或用户代理。

