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

我在Java中使用Spring框架构建了一个Web服务,并在localhost上的tc服务器上运行。 我使用curl测试了Web服务,它可以工作。 换句话说,此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}' 

现在,我正在使用RoR构建一个Web应用程序,并希望做类似的事情。 我该如何构建它? 基本上,RoR Web应用程序将是发布到Web服务的客户端。

搜索SO和网络,我发现了一些有用的链接,但我无法让它工作。 例如,从这篇文章中 ,他/她使用net / http。

我试过但它不起作用。 在我的控制器中,我有

  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 

它返回错误:

 undefined local variable or method `url_path' for # 

我正在使用的示例代码来自此处

我没有附加到net / http,我不介意使用其他工具,只要我能轻松完成相同的任务。

非常感谢!

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

您的问题正是解释器告诉您的问题:url_path未声明。 你想要的是在上一行中声明的url变量上调用#path方法。

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

应该管用。