Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

ruby on rails - How do I post XML to RESTFUL Web Service using Net::HTTP::Post?

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:

<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:

<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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...