Dave Dave - 1 year ago 118
Ruby Question

How do you add headers to a Net::Http::Post request in Ruby?

I’m using Rails 4.2.7. How do I add headers to a Net::HTTP::Post request? I tried

params = {"SubmitButton" => "View"}

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

However when I run this code I get the error

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'

Note I want to add the headers to the object before it is sent.

Answer Source

Do it like this

      headers = {"Referer" => url}
      req = Net::HTTP::Post.new(uri)
      headers.each do |key, array|
        req[key] = array
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download