2011-09-07 103 views
1

我在Java中使用Spring框架构建了Web服务,并使其在localhost上的tc服务器上运行。我使用curl测试了Web服务,它工作正常。换句话说,这个curl命令会向web服务发布一个新的事务。使用Ruby on Rails将JSON/XML数据发布到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和网上搜索,我发现了一些有用的链接,但是我无法使它工作。例如,从这个post,他/她使用净/ 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 #<TransactionsController:0x0000010287ed28> 

我使用的示例代码是从here

我没有连接到网/ http和我不只要我能轻松完成相同的任务,就不要介意使用其他工具。

非常感谢!

回答

1
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) 

应该工作。

+0

谢谢,但它不起作用。我不完全是。它不会返回任何错误消息,但是Web服务端没有任何事情发生 – okysabeni