Curl::Easy を使用header_str
すると、返されたヘッダーに文字列としてアクセスできます。ドキュメントから:
実行する前の呼び出しからの応答ヘッダーを返します。これは、デフォルトの on_header ハンドラーによって設定されます。独自のヘッダー ハンドラーを指定すると、この文字列は空になります。
これをテストするために、次を使用して組み込みの Gem サーバーをオンにしました。
gem server
これをテストするコードは次のとおりです。
curl = Curl::Easy.http_get('http://0.0.0.0:8808')
curl.header_str
=> "HTTP/1.1 200 OK \r\nDate: 2013-01-10 09:07:42 -0700\r\nContent-Type: text/html\r\nServer: WEBrick/1.3.1 (Ruby/1.9.3/2012-11-10)\r\nContent-Length: 62164\r\nConnection: Keep-Alive\r\n\r\n"
応答をキャプチャし、残りの文字列をハッシュに分割して使いやすくするのは簡単です。
http_response, *http_headers = curl.header_str.split(/[\r\n]+/).map(&:strip)
http_headers = Hash[http_headers.flat_map{ |s| s.scan(/^(\S+): (.+)/) }]
http_response # => "HTTP/1.1 200 OK"
http_headers
=> {
"Date" => "2013-01-10 09:07:42 -0700",
"Content-Type" => "text/html",
"Server" => "WEBrick/1.3.1 (Ruby/1.9.3/2012-11-10)",
"Content-Length" => "62164",
"Connection" => "Keep-Alive"
}
Pry で再度テストします。
[27] (pry) main: 0> curl = Curl::Easy.http_get('http://www.example.com')
#<Curl::Easy http://www.example.com>
[28] (pry) main: 0> curl.header_str
"HTTP/1.0 302 Found\r\nLocation: http://www.iana.org/domains/example/\r\nServer: BigIP\r\nConnection: Keep-Alive\r\nContent-Length: 0\r\n\r\n"
[29] (pry) main: 0> http_response, *http_headers = curl.header_str.split(/[\r\n]+/).map(&:strip)
[
[0] "HTTP/1.0 302 Found",
[1] "Location: http://www.iana.org/domains/example/",
[2] "Server: BigIP",
[3] "Connection: Keep-Alive",
[4] "Content-Length: 0"
]
[30] (pry) main: 0> http_headers = Hash[http_headers.flat_map{ |s| s.scan(/^(\S+): (.+)/) }]
{
"Location" => "http://www.iana.org/domains/example/",
"Server" => "BigIP",
"Connection" => "Keep-Alive",
"Content-Length" => "0"
}