【问题标题】:Convert Curl command line in Rails在 Rails 中转换 Curl 命令行
【发布时间】:2014-02-06 08:29:02
【问题描述】:

这是我的 curl 命令,在命令行中运行良好:

curl --data @order_new.json \
     -H "X-Augury-Token:My_token_goes_here" \
     -H "Content-Type:application/json" \
     http://staging.hub.spreecommerce.com/api/stores/store_id_goes_here/messages

我需要使用任何类型的 Gem 在 Rails 中实现相同的功能,尝试使用 HTTParty /rest_client / spree-api-client,但这里出了点问题:

require 'httparty'

result = HTTParty.post(
        "http://staging.hub.spreecommerce.com/api/stores/52eb347f755b1c97e900001e/messages",
        :body => JSON.parse(File.read("order_new.json")),
        :header => {
           "X-Augury-Token" => "UjjKsdxbrwjpAPx9Hiw4",
           "Content-Type" => "application/json" 
        }
)

但我收到错误,

"The page you were looking for doesn't exist (404)"

我需要与上面 curl 命令等效的 rails,使用 spree-api-client gem 会很有帮助。

【问题讨论】:

  • Curl 正在执行 get 请求,http 方正在执行 post 请求。
  • 我怀疑@andHapp,curl 命令会发送--data 参数,所以它应该是POST 请求,而不是GET 请求。
  • 哦对了..抱歉错过了!

标签: ruby-on-rails curl rest-client httparty


【解决方案1】:

如果您更喜欢使用Spree::API::Client,您能否发布您的发现结果?您能否评估以下命令的输出并回复:

client = Spree::API::Client.new('http://staging.hub.spreecommerce.com/api/', 'UjjKsdxbrwjpAPx9Hiw4')
client.products.inspect

【讨论】:

  • 我已经在 github 链接中看到过这样的内容,但是如何像 curl 一样传递 -header、-data 属性。
  • 您不需要这样做。这个 gem 不是 curl 命令的替代品,它是一个可以用来与 spree 通信的客户端。如果您尝试创建订单,您应该可以使用client.create_order(data) 来完成。查看代码以了解发生了什么:github.com/andrew/spree-api-client/blob/master/lib/…github.com/andrew/spree-api-client/blob/master/lib/…github.com/andrew/spree-api-client/blob/master/lib/…
  • 是的,我明白了你的意思,使用 client.create_order(data),我们可以在我们的店面中 create_order (spree),但它不会明确地将任何消息传递给集线器。但根据我的问题,我需要将类似的通知消息传递给我的集线器(staging.hub.spreecommerce.com/)! :)
  • 啊,对不起。我不熟悉 Spreecommerce 中心,但我已经调查过了。这不就是你要找的吗? github.com/spree/spree_hub_connector
【解决方案2】:
require 'httparty'

result = HTTParty.post(
        "http://staging.hub.spreecommerce.com/api/stores/52eb347f755b1c97e900001e/messages",
        :body => @order.to_json,
        :header => {
           "X-Augury-Token" => "UjjKsdxbrwjpAPx9Hiw4",
           "Content-Type" => "application/json" 
        }
)

传递给 HTTParty 正文时不要解析 json

【讨论】:

  • GOT ERROR: NoMethodError: undefined method `json' for nil:NilClass 让我们忘记添加 .json 文件作为输入,我们可以在 :body 部分传递一个对象吗?就像 :body => Order.last ?
  • 你必须在 body 中传递 json,所以在 \@order 中加载 order 并写入 \@order.to_json
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多