Set request headers


Finally we get to the point where we can set the headers in the request. Actually it is pretty easy to do so. We just need to pass a new parameter called initheader with a hash of the header keys and values we would like to set.

This way we can add new fields to the header and we can replace existing ones. For example here we set the User-Agent to Internet Explorer 6.0.


examples/net-http/set_request_headers_httpbin.rb
require 'net/http'

url = 'https://httpbin.org/headers'
uri = URI(url)
# puts(uri)

response = Net::HTTP.get_response(uri, initheader = {
    "Accept"     => "json",
    "Auth"       => "secret",
    "User-Agent" => "Internet Explorer 6.0",
  })
if response.is_a?(Net::HTTPSuccess)
    #puts "Headers:"
    #puts response.to_hash.inspect
    #puts '------'
    puts response.body
else
    puts response.code
end

In the response we can see that the fields were set as expected.


{
  "headers": {
    "Accept": "json", 
    "Accept-Encoding": "gzip;q=1.0,deflate;q=0.6,identity;q=0.3", 
    "Auth": "secret", 
    "Host": "httpbin.org", 
    "User-Agent": "Internet Explorer 6.0", 
    "X-Amzn-Trace-Id": "Root=1-6394bdbc-24b60d3376d56a493049d2e5"
  }
}

As you might know every time you access a web site it will log the request in a log file, usually including the User-Agent as well. This way you could generate lots of request to a web site making their stats show that Internet Explorer 6.0 is back in popularity.

Don't do it!