Add headers to a request in rails

I find this more readable

require "net/http"
require "uri"

url = URI.parse("http://www.whatismyip.com/automation/n09230945.asp")

req = Net::HTTP::Get.new(url.path)
req.add_field("X-Forwarded-For", "0.0.0.0")
req.add_field("Accept", "*/*")

res = Net::HTTP.new(url.host, url.port).start do |http|
  http.request(req)
end

puts res.body

stolen from http://www.dzone.com/snippets/send-custom-headers-rub

HOWEVER !!

if you want to send 'Accept' header (Accept: application/json) to Rails application, you cannot do:

req.add_field("Accept", "application/json")

but do:

req['Accept'] = 'application/json'

The reason for this that Rails ignores the Accept header when it contains “,/” or “/,” and returns HTML (which add_field adds). This is due to really old browsers sending incorrect "Accept" headers.


It can be set on the request object:

request = Post.new(url)
request.form_data = params
request['X-Forwarded-For'] = '203.0.113.195'
request.start(url.hostname, url.port,
        :use_ssl => url.scheme == 'https' ) {|http|
    http.request(request) }

See these Net::HTTP examples:

https://github.com/augustl/net-http-cheat-sheet/blob/master/headers.rb