2013-02-06 160 views
13

響應頭我使用網絡進行使用Ruby HTTP請求:: HTTP,我無法弄清楚如何讓所有的響應頭。獲得在Ruby HTTP請求

我試圖response.headerresponse.headers並沒有什麼工作。

+0

網絡/ HTTP有一個臭名昭着的糟糕的API。如果你使用另一個,比如httpclient,'response.header'就可以工作。 –

+0

你的意思是壞的?爲什麼我想避免它? – BlackHatSamurai

+0

圖書館本身並不壞,但是API是笨重,不直觀,你已經發現。當我可以的時候,我總是使用httpclient或包含更多功能的包裝庫,如HTTParty,Rest-Client等。 –

回答

36

響應對象實際上包含的標頭。

請參閱 「Net::HTTPResponse」 的更多資料。

你可以這樣做:

response['Cache-Control'] 

您也可以撥打each_headereach響應對象通過頭進行迭代。

如果你真的想響應對象以外的頭,叫response.to_hash

2

注意,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" 
} 
0

響應Net::HTTPResponse包含Net::HTTPHeader頭,你可以從由@Intrepidd說each_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" 
}