在HTTparty中传递标题和查询参数

时间:2014-07-11 06:37:48

标签: ruby-on-rails ruby http-headers httparty

如何使用HTTparty在post方法中传递查询参数和标题。我这样做 但它抛出

query = {:method => "neworder", :nonce => 1404996028, :order_type => "buy", :quantity=>1,:rate=>1}
headers = {:key=> "87819747209090199871234", :sign=> "0a3888ac7f8e411ad73a0a503c55db70a291rsf34bfb9f9a47147d5200882674f717f6ede475669f3453"}

HTTParty.post("https://www.acb.com/api/v2/market/LTC_BTC/", :query => query, :headers => headers )

但它会引发以下错误。如何使用HTTparty处理查询字符串参数和标题。

/home/user/.rvm/rubies/ruby-2.1.0/lib/ruby/2.1.0/net/http/header.rb:172:in `capitalize': undefined method `split' for :key:Symbol (NoMethodError)
from /home/user/.rvm/rubies/ruby-2.1.0/lib/ruby/2.1.0/net/http/header.rb:165:in `block in each_capitalized'
from /home/user/.rvm/rubies/ruby-2.1.0/lib/ruby/2.1.0/net/http/header.rb:164:in `each'
from /home/user/.rvm/rubies/ruby-2.1.0/lib/ruby/2.1.0/net/http/header.rb:164:in `each_capitalized'

2 个答案:

答案 0 :(得分:85)

使用Strings代替哈希键而不是Symbols

query = { 
  "method"     => "neworder",
  "nonce"      => 1404996028,
  "order_type" => "buy",
  "quantity"   => 1,
  "rate"       => 1
}
headers = { 
  "key"  => "8781974720909019987",
  "sign" => "0a3888ac7f8e411ad73a0a503c55db70a291bfb9f9a47147d5200882674f717f6ede475669f3453" 
}

HTTParty.post(
  "https://www.acb.com/api/v2/market/LTC_BTC/", 
  :query => query,
  :headers => headers
)

由于net/http/header.rb:172中发生错误,可能只有headers导致问题。重要信息为undefined method 'split' for :key:Symbol (NoMethodError)

irb中的符号错误:

irb(main):002:0> "Something".split
=> ["Something"]

irb(main):003:0> :Something.split
NoMethodError: undefined method `split' for :Something:Symbol
        from (irb):3
        from /usr/bin/irb:12:in `<main>'

答案 1 :(得分:7)

这是一个有点老问题,但最近我们遇到了同样的问题,所以我尝试附上我的解决方案:

1)上面的答案正在起作用:

  "headers": {
      "Authorization" => "Bearer #{token}"
    }

2)或者,另一种解决方案是:

  headers: {
      Authorization: "Bearer #{token}"
    }