我正在使用Net :: HTTP向Ruby发出HTTP请求,我无法弄清楚如何获取所有响应头.
我试过了response.header
,但response.headers
没有任何工作.
Int*_*idd 47
响应对象实际上包含标头.
有关详细信息,请参阅" Net :: HTTPResponse ".
你可以做:
response['Cache-Control']
Run Code Online (Sandbox Code Playgroud)
您还可以调用each_header
或each
在响应对象上迭代标头.
如果你真的想要在响应对象之外的标题,请调用 response.to_hash
Gok*_*l M 14
响应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"]
]
Run Code Online (Sandbox Code Playgroud)
您可以使用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"
}
Run Code Online (Sandbox Code Playgroud)