【问题标题】:Rails 3 Post to external web serviceRails 3 发布到外部网络服务
【发布时间】:2013-02-22 23:28:33
【问题描述】:

假设我有一个用户正在创建的博客文章,我想将所有数据作为具有特定架构的 XML 发送到外部 Web 服务,以便可以将其摄取到该 Web 服务中。

我一直在研究 ActionDispatch::Request

我读了这个Using Ruby on Rails to POST JSON/XML data to a web service 的帖子和回答

但是我收到一条错误消息,提示 content_type 不是有效的请求方法。所以我更改了该行以调用 header 方法并使用适当的信息为 content-type 创建一个标题

好的...那么现在去哪里?

这是我目前的代码:

url= URI.parse('http://10.29.3.47:8080/ingest')
response = Net::HTTP::Post.new(url.path)
request.headers["Content-Type"] = 'application/json'
request.body = 'all of my xml data and schema which is far too long to type here'
response = Net::HTTP.start(url.host, url.port) {|http| http.request(request)}
assert_equal '201 Created', response.get_fields('Status')

我收到一条错误消息,说 request.body 也不是有效的方法调用,但是当我查看 API 时,唯一匹配 body 的是不带参数的“body()”。那么如何将我的帖子内容传递给网络服务呢?

感谢您的帮助!

【问题讨论】:

标签: ruby-on-rails json web-services


【解决方案1】:

你有response = Net::HTTP::Post.new(url.path)而不是request = Net::HTTP::Post.new(url.path),你有add标头和add_field

require 'net/http'
require 'uri'
url= URI.parse('http://10.29.3.47:8080/ingest')
request = Net::HTTP::Post.new(url.path)
request.add_field 'Content-Type', 'application/json'
request.body = 'all of my xml data and schema which is far too long to type here'
response = Net::HTTP.start(url.host, url.port) {|http| http.request(request)}

【讨论】:

    猜你喜欢
    • 2014-08-24
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 2013-07-28
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多