使用 Ruby on Rails 将 JSON/XML 数据发布到 Web 服务 [英] Using Ruby on Rails to POST JSON/XML data to a web service
问题描述
我使用 Java 中的 Spring 框架构建了一个 Web 服务,并让它在本地主机上的 tc 服务器上运行.我使用 curl 测试了 Web 服务并且它工作正常.换句话说,此 curl 命令将向 Web 服务发布新事务.
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}'
现在,我正在使用 RoR 构建一个 Web 应用程序,并且想做类似的事情.我怎样才能建立它?基本上,RoR Web 应用程序将是一个向 Web 服务发送消息的客户端.
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.
搜索 SO 和网络,我找到了一些有用的链接,但我无法让它工作.例如,从这个post,他/她使用 net/http.
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
返回错误:
undefined local variable or method `url_path' for #<TransactionsController:0x0000010287ed28>
我使用的示例代码来自这里一个>
我不依赖于 net/http,我不介意使用其他工具,只要我可以轻松完成相同的任务.
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.
非常感谢!
推荐答案
url = URI.parse('http://localhost:8080/BarcodePayment/transactions/')
response = Net::HTTP::Post.new(url_path)
您的问题正是解释器告诉您的问题:url_path 未声明.您想要的是对您在上一行中声明的 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)
应该可以.
这篇关于使用 Ruby on Rails 将 JSON/XML 数据发布到 Web 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!