Get response headers from Ruby HTTP request

The response object actually contains the headers.

See "Net::HTTPResponse" for more infomation.

You can do:

response['Cache-Control']

You can also call each_header or each on the response object to iterate through the headers.

If you really want the headers outside of the response object, call response.to_hash


The response Net::HTTPResponse contains headers from Net::HTTPHeader which you can get from each_header method as said by @Intrepidd which will return an enumerator as below:

response.each_header

#<Enumerator: #<Net::HTTPOK 200 OK readbody=true>:each_header>
[
  ["x-frame-options", "SAMEORIGIN"],
  ["x-xss-protection", "1; mode=block"],
  ["x-content-type-options", "nosniff"],
  ["content-type", "application/json; charset=utf-8"],
  ["etag", "W/\"51a4b917285f7e77dcc1a68693fcee95\""],
  ["cache-control", "max-age=0, private, must-revalidate"],
  ["x-request-id", "59943e47-5828-457d-a6da-dbac37a20729"],
  ["x-runtime", "0.162359"],
  ["connection", "close"],
  ["transfer-encoding", "chunked"]
]

You can get the actual hash using to_h method as below:

response.each_header.to_h

{
  "x-frame-options"=>"SAMEORIGIN", 
  "x-xss-protection"=>"1; mode=block", 
  "x-content-type-options"=>"nosniff", 
  "content-type"=>"application/json; charset=utf-8", 
  "etag"=>"W/\"51a4b917285f7e77dcc1a68693fcee95\"", 
  "cache-control"=>"max-age=0, private, must-revalidate", 
  "x-request-id"=>"59943e47-5828-457d-a6da-dbac37a20729", 
  "x-runtime"=>"0.162359", 
  "connection"=>"close", 
  "transfer-encoding"=>"chunked"
}

Note that the RestClient library has the expected behaviour for response.headers.

response.headers
{
                          :server => "nginx/1.4.7",
                            :date => "Sat, 08 Nov 2014 19:44:58 GMT",
                    :content_type => "application/json",
                  :content_length => "303",
                      :connection => "keep-alive",
             :content_disposition => "inline",
     :access_control_allow_origin => "*",
          :access_control_max_age => "600",
    :access_control_allow_methods => "GET, POST, PUT, DELETE, OPTIONS",
    :access_control_allow_headers => "Content-Type, x-requested-with"
}