29

Net :: HTTPを使用してRubyでHTTPリクエストを作成していますが、すべての応答ヘッダーを取得する方法がわかりません。

試しresponse.headerてみresponse.headersましたが、何も機能していません。

4

6 に答える 6

57

応答オブジェクトには、実際にはヘッダーが含まれています。

詳細については、「Net::HTTPResponse」を参照してください。

できるよ:

response['Cache-Control']

each_headerまたはeach、応答オブジェクトを呼び出して、ヘッダーを反復処理することもできます。

応答オブジェクトの外部にヘッダーが本当に必要な場合は、response.to_hash

于 2013-02-06T00:38:43.360 に答える
15

応答には、@ Intrepiddが言うように、メソッドから取得できるNet::HTTPResponseヘッダーが含まれています。このヘッダーは、次のように列挙子を返します。Net::HTTPHeadereach_header

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 に答える