Gooner
Gooner

Reputation: 1590

Unable to execute http POST with XML data in Ruby on Rails

I am trying to pass data from the database in XML format to an API. I've written the following code in the controller.

require 'active_support/builder' unless defined?(Builder)
require 'uri'
require 'net/http'

 def gen_xml
      xml = Builder::XmlMarkup.new
      @customers = Customer.find(:all)

      url = "http://.......................xml?";

      request = Net::HTTP::Post.new(url)
      request.add_field "Content-Type", "application/xml"
      request.body = xml

      uri = URI.parse(url)
      http = Net::HTTP.new(uri.host, uri.port)
      response = http.request(request)
  end

I have created a XML file with XML builder, but I'm not able to pass this XML data to the API. The above code doesn't leave any trace of error or any respective action being preformed in the logs.

Upvotes: 1

Views: 3221

Answers (1)

Gooner
Gooner

Reputation: 1590

Hey ! Finally figured it out

I am able to pass the data to API by making the following changes:

1)Initially, the XML data was copied into a string by

x = Builder::XmlMarkup.new(:target => out_string = "<?xml version='1.0' encoding='UTF-8'?>\n", :indent =>1) 

2) Later, used this 'out_string' to pass xml data. via request.body = out_string; as follows ,

   uri = URI.parse("http:............")

        http = Net::HTTP.new(uri.host, uri.port)
        request = Net::HTTP::Post.new(uri.request_uri)
        request.body = out_string

        response = http.request(request)

Upvotes: 4

Related Questions