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

我的梦境 提交于 2019-12-11 07:43:50

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/7340052/using-ruby-on-rails-to-post-json-xml-data-to-a-web-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!