【问题标题】:Using Ruby on Rails to POST JSON/XML data to a web service使用 Ruby on Rails 将 JSON/XML 数据发布到 Web 服务
【发布时间】:2011-11-12 11:51:13
【问题描述】:

我在 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 和网络,我发现了一些有用的链接,但我无法让它工作。例如,从这个post,他/她使用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 #<TransactionsController:0x0000010287ed28>

我使用的示例代码来自here

我不依赖net/http,我不介意使用其他工具,只要我可以轻松完成相同的任务。

非常感谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 post net-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)
    

    应该可以。

    【讨论】:

    • 谢谢,但它不起作用。我不完全是。它不返回任何错误消息,但 Web 服务端没有发生任何事情
    猜你喜欢
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多