简体   繁体   English

使用Ruby on Rails将JSON / XML数据发布到Web服务

[英]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. 我使用Java中的Spring框架构建了一个Web服务,并使其在localhost的tc服务器上运行。 I tested the web service using curl and it works. 我使用curl测试了Web服务,它可以工作。 In other words, this curl command will post a new transaction to the web service. 换句话说,该curl命令会将新事务发布到Web服务。

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. 现在,我正在使用RoR构建一个Web应用程序,并希望做类似的事情。 How can I build that? 我该如何建造? Basically, the RoR web app will be a client that posts to the web service. 基本上,RoR Web应用程序将是发布到Web服务的客户端。

Searching SO and the web, I found some helpful links but I cannot get it to work. 搜索SO和网络时,我发现了一些有用的链接,但无法正常工作。 For example, from this post , he/she uses net/http. 例如,在此帖子中 ,他/她使用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. 我不隶属于net / http,只要可以轻松完成同一任务,就不介意使用其他工具。

Thanks much! 非常感谢!

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. 您的问题正是解释器告诉您的问题:url_path未声明。 what you want is to call the #path method on the url variable you declared in the previous line. 您要在上一行中声明的url变量上调用#path方法。

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

should work. 应该管用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM