Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add headers to a request in rails

I'm using Rails 3.2.1 to make an HTTP Post.

I need to add X-FORWARDED FOR to the header. How do I do that in Rails?

Code:

post_data = {
  "username" => tabuser
}

response = Net::HTTP.post_form(URI.parse("http://<my php file>"), post_data)
like image 761
Tyler DeWitt Avatar asked Feb 15 '12 23:02

Tyler DeWitt


People also ask

What are headers in HTTP requests?

An HTTP header is a field of an HTTP request or response that passes additional context and metadata about the request or response. For example, a request message can use headers to indicate it's preferred media formats, while a response can use header to indicate the media format of the returned body.

What is a request header in Java?

A request header is an HTTP header that can be used in an HTTP request to provide information about the request context, so that the server can tailor the response. For example, the Accept-* headers indicate the allowed and preferred formats of the response.


2 Answers

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.

like image 107
equivalent8 Avatar answered Sep 22 '22 04:09

equivalent8


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

like image 36
house9 Avatar answered Sep 22 '22 04:09

house9