I'm making an HTTP request with Ruby using Net::HTTP, and I can't figure out how to get all the response headers.
I tried response.header
and response.headers
and nothing is working.
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"
}
If you need user friendly output then each_capitalized
can be used:
response.each_capitalized { |key, value| puts " - #{key}: #{value}" }
This will print:
- Content-Type: application/json; charset=utf-8
- Transfer-Encoding: chunked
- Connection: keep-alive
- Status: 401 Unauthorized
- Cache-Control: no-cache
- Date: Wed, 28 Nov 2018 09:06:39 GMT
This is also easily achieved with HTTParty as an alternative:
HTTParty.get(uri).headers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With