29

我正在使用 Net::HTTP 向 Ruby 发出 HTTP 请求,但我不知道如何获取所有响应标头。

我试过了response.headerresponse.headers但没有任何效果。

4

6 回答 6

57

响应对象实际上包含标头。

有关更多信息,请参阅“ Net::HTTPResponse ”。

你可以做:

response['Cache-Control']

您还可以在响应对象上调用each_headereach来遍历标头。

如果您真的想要响应对象之外的标头,请调用response.to_hash

于 2013-02-06T00:38:43.360 回答
15

响应Net::HTTPResponse包含标题Net::HTTPHeader,您可以从each_header@Intrepidd 所说的方法中获取这些标题,该方法将返回一个枚举器,如下所示:

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

您可以使用以下方法获取实际哈希to_h

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"
}
于 2018-02-16T05:49:07.610 回答
4

请注意,该RestClient库具有预期的行为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"
}
于 2014-11-08T19:55:22.937 回答
4

如果您需要用户友好的输出,则each_capitalized可以使用:

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

这将打印:

 - 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
于 2018-11-28T09:10:20.820 回答
0

将其存储在哈希中 =>

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

puts response_headers
于 2019-10-16T10:15:58.317 回答
0

使用HTTParty作为替代方案也很容易实现这一点:

HTTParty.get(uri).headers
于 2020-07-04T02:59:07.533 回答