oky_sabeni
oky_sabeni

Reputation: 7822

Using Ruby on Rails to POST JSON/XML data to a web service

I built a web service in using Spring framework in Java and have it run on a tc server on localhost. I tested the web service using curl and it works. In other words, this curl command will post a new transaction to the web service.

curl -X POST -H 'Accept:application/json' -H 'Content-Type: application/json' http://localhost:8080/BarcodePayment/transactions/ --data '{"id":5,"amount":5.0,"paid":true}'

Now, I am building a web app using RoR and would like to do something similar. How can I build that? Basically, the RoR web app will be a client that posts to the web service.

Searching SO and the web, I found some helpful links but I cannot get it to work. For example, from this post, he/she uses net/http.

I tried but it doesn't work. In my controller, I have

  require 'net/http'
  require "uri"

 def post_webservice
      @transaction = Transaction.find(params[:id])
      @transaction.update_attribute(:checkout_started, true);

      # do a post service to localhost:8080/BarcodePayment/transactions
      # use net/http
      url = URI.parse('http://localhost:8080/BarcodePayment/transactions/')
      response = Net::HTTP::Post.new(url_path)
      request.content_type = 'application/json'
      request.body = '{"id":5,"amount":5.0,"paid":true}'
      response = Net::HTTP.start(url.host, url.port) {|http| http.request(request) }

      assert_equal '201 Created', response.get_fields('Status')[0]
    end

It returns with error:

undefined local variable or method `url_path' for #<TransactionsController:0x0000010287ed28>

The sample code I am using is from here

I am not attached to net/http and I don't mind using other tools as long as I can accomplish the same task easily.

Thanks much!

Upvotes: 1

Views: 6177

Answers (1)

Jason Lewis
Jason Lewis

Reputation: 1314

url = URI.parse('http://localhost:8080/BarcodePayment/transactions/')
response = Net::HTTP::Post.new(url_path)

Your problem is exactly what the interpreter told you it is: url_path is undeclared. what you want is to call the #path method on the url variable you declared in the previous line.

url = URI.parse('http://localhost:8080/BarcodePayment/transactions/')
response = Net::HTTP::Post.new(url.path)

should work.

Upvotes: 2

Related Questions