web-dev-qa-db-fra.com

Obtenez les en-têtes de réponse de Ruby requête HTTP

Je fais une demande HTTP avec Ruby en utilisant Net :: HTTP, et je ne peux pas comprendre comment obtenir tous les en-têtes de réponse.

J'ai essayé response.header et response.headers et rien ne fonctionne.

24
BlackHatSamurai

L'objet de réponse contient en fait les en-têtes.

Voir " Net :: HTTPResponse " pour plus d'informations.

Tu peux faire:

response['Cache-Control']

Vous pouvez également appeler each_header ou each sur l'objet réponse pour parcourir les en-têtes.

Si vous voulez vraiment les en-têtes en dehors de l'objet de réponse, appelez response.to_hash

48
Intrepidd

La réponse Net::HTTPResponse contient des en-têtes de Net::HTTPHeader que vous pouvez obtenir auprès de each_header méthode comme dit par @Intrepidd qui retournera un énumérateur comme ci-dessous:

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"]
]

Vous pouvez obtenir le hachage réel en utilisant to_h méthode comme ci-dessous:

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"
}
5
Gokul M

Notez que la bibliothèque RestClient a le comportement attendu pour 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"
}
3
Dennis

Si vous avez besoin d'une sortie conviviale alors each_capitalized peut être utilisé:

response.each_capitalized { |key, value| puts " - #{key}: #{value}" }

Cela imprimera:

 - 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
2
Vlad

Pour le stocker dans un hachage =>

response_headers = {}
your_object.response.each { |key, value|  response_headers.merge!(key.to_s => value.to_s) }

puts response_headers
0
Prashanth Sams