TECHLOGICS

HYLOGICS分室。作業メモやガジェットのレビューなど、主に技術系のエントリを取り扱います。

rubyでヘッダ情報を取得する

「Last-Modifiedが欲しいんだけど」以下略

#! /usr/local/bin/ruby

require 'net/http'

http = Net::HTTP.new('www.yahoo.co.jp')

res = http.head('/')

res.each do | key, value |
  p "#{key} = #{value}"
end
"server = nginx"
"date = Thu, 05 May 2016 17:25:30 GMT"
"content-type = text/html; charset=UTF-8"
"connection = close"
"p3p = policyref=\"http://privacy.yahoo.co.jp/w3c/p3p_jp.xml\", CP=\"CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV\""
"x-content-type-options = nosniff"
"x-xss-protection = 1; mode=block"
"x-frame-options = SAMEORIGIN, SAMEORIGIN"
"cache-control = private, no-cache, no-store, must-revalidate"
"expires = -1"
"pragma = no-cache"
"x-xrds-location = https://open.login.yahooapis.jp/openid20/www.yahoo.co.jp/xrds"
"vary = Accept-Encoding"

ちなみに全てString型なので

#! /usr/local/bin/ruby

require 'net/http'
require 'date'

http = Net::HTTP.new('www.yahoo.co.jp')

res = http.head('/')

p res['date']
p res['date'].class

p res['date']
p DateTime.parse(res['date']).class
"Thu, 05 May 2016 17:22:29 GMT"
String
"Thu, 05 May 2016 17:22:29 GMT"
DateTime