Dave
Dave

Reputation: 19110

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.

Upvotes: 1

Views: 5771

Answers (2)

Milo P
Milo P

Reputation: 1462

Aside from T J's method (providing the headers as a parameter to the post() call), you can also set the headers on the HTTPRequest object itself using :[]:

uri = URI('http://example.com/cached_response')
req = Net::HTTP::Get.new(uri)
req['If-Modified-Since'] = file.mtime.rfc2822

Source: https://ruby-doc.org/stdlib-2.3.8/libdoc/net/http/rdoc/Net/HTTP.html#class-Net::HTTP-label-Setting+Headers

This allows you to set the headers outside of performing the request.

The same approach works for Net::HTTP::Post objects:

params = {"SubmitButton" => "View"}
req = Net::HTTP::Post.new(uri, params)
req['Referer'] = url

Upvotes: 0

T J
T J

Reputation: 1342

You can use the instance to make the post with headers

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

Upvotes: 5

Related Questions