如何在Ruby中向Net :: Http :: Post请求添加标头?

时间:2016-09-14 14:30:03

标签: ruby-on-rails ruby post http-headers net-http

我正在使用Rails 4.2.7。如何将标头添加到Net :: HTTP :: Post请求?我试过了

    params = {"SubmitButton" => "View"}
    …
      headers = {"Referer" => url}
      req = Net::HTTP::Post.new(uri, params.to_query, headers)

然而,当我运行此代码时,我收到错误

Error during processing: wrong number of arguments (given 3, expected 1..2)
/Users/davea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http/request.rb:14:in `initialize'
/Users/davea/Documents/workspace/myproject/app/services/marathon_guide_race_finder_service.rb:97:in `new'
/Users/davea/Documents/workspace/myproject/app/services/marathon_guide_race_finder_service.rb:97:in `block in process_race_link'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/node_set.rb:187:in `block in each'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/node_set.rb:186:in `upto'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/node_set.rb:186:in `each'

注意我想在发送之前将标题添加到对象中。

1 个答案:

答案 0 :(得分:2)

您可以使用该实例制作带标题的帖子

headers  = {"Referer" => url}
http     = Net::HTTP.new(uri.host)
response = http.post(uri.path, params.to_query, headers)