ruby – 使用Open :: URI显示HTTP标头?

前端之家收集整理的这篇文章主要介绍了ruby – 使用Open :: URI显示HTTP标头?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用Open :: URI,我可以执行以下操作:
require 'open-uri'
#check status
open('http://google.com').status
#get entire html
open('http://google.com').read

是否有可能获取请求的HTTP标头,以便可以调试内容,例如Curls的curl -I http://google.com?

$curl -I google.com
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Mon,17 Dec 2012 14:28:17 GMT
Expires: Wed,16 Jan 2013 14:28:17 GMT
Cache-Control: public,max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN

这可能吗?

解决方法

使用虚拟文件句柄的元方法
open('http://google.com'){|f| pp f.Meta  }
{"x-frame-options"=>"SAMEORIGIN","expires"=>"-1","p3p"=>
  "CP=\"This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info.\"","content-type"=>"text/html; charset=ISO-8859-1","date"=>"Mon,17 Dec 2012 14:37:29 GMT","server"=>"gws","x-xss-protection"=>"1; mode=block","set-cookie"=>
  "PREF=ID=d2fb8a93d369bcd2:FF=0:TM=1355755049:LM=1355755049:S=ONVSP6n2jtluFgll; expires=Wed,17-Dec-2014 14:37:29 GMT; path=/; domain=.google.com,NID=67=OFEvvHCOa3C6wScQCUIKfu_89oL9MSmnFjwN-u5LX_foP8NLsX7G9dq48NLVrf4WUXhqOA1jb38s0e9qeRp1Iwx_LT_N8IuF0Qi6dXVtR2zdvA86INqtfg5uNrKvxJfJ; expires=Tue,18-Jun-2013 14:37:29 GMT; path=/; domain=.google.com; HttpOnly","cache-control"=>"private,max-age=0","transfer-encoding"=>"chunked"}

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/open-uri/rdoc/OpenURI/Meta.html

原文链接:https://www.f2er.com/ruby/268946.html

猜你在找的Ruby相关文章