How do I post XML to RESTFUL Web Service using Net::HTTP::Post?

21,948

Solution 1

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?

Solution 2

If I were you, I'd use Wireshark, tcpflow or 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.

Share:
21,948
Aaron N. Brock
Author by

Aaron N. Brock

Updated on May 22, 2020

Comments

  • Aaron N. Brock
    Aaron N. Brock almost 4 years

    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?

  • Aaron N. Brock
    Aaron N. Brock about 15 years
    Yea! Thanks, I needed to add the following line and it worked: request.content_type = 'text/xml'