In Ruby, how can I get hold of the HTTP Request Headers that will be sent by a net/http(s) or open-uri request BEFORE it actually makes the request.
In some cases, headers are used when creating a signed string in a URI. Surely there is some way to acquire the request headers that will be sent. These should include the "Host:" header for example.
see http://ruby-doc.org/stdlib-2.0/libdoc/net/http/rdoc/Net/HTTP.html#label-Setting+Headers
Works well in ruby 2.0.0 - but you are correct, different behavior in 1.9.3
Ruby 2.0.0
require 'net/http'
uri = URI('http://github.com/ruby')
http_request = Net::HTTP::Get.new(uri)
http_request.each_header { |header| puts header }
# => accept-encoding
# => accept
# => user-agent
# => host
http_response = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(http_request)
end
Ruby 1.9.3
require 'uri'
require 'net/http'
uri = URI.parse('http://github.com/ruby')
http_request = Net::HTTP::Get.new(uri.path)
http_request.each_header { |header| puts header }
# => accept
# => user-agent
http_response = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(http_request)
end
http_request.each_header { |header| puts header }
# => accept
# => user-agent
# => host
The Net::HTTP classes all seem to use Net::HTTPHeader as a mixin. You should be able to use to_hash() on the request object to get all headers at once, or each_header() / each() to iterate one header at a time.