2011-06-09 67 views
5

我目前得到使用页面的源代码:的Net :: HTTP GET源代码和状态

Net::HTTP.get(URI.parse(page.url)) 

我也想获得HTTP状态,而不进行第二次请求。

有没有办法用另一种方法做到这一点?我一直在看文档,但似乎无法找到我在找什么。

回答

2

对不起,实际上已经想通了:)。

ruby-1.9.2-p136 :004 > r = Net::HTTP.get_response(URI.parse('http://badurlexample.com')) 
=> #<Net::HTTPInternalServerError 500 Internal Server Error readbody=true> 
ruby-1.9.2-p136 :005 > r.inspect 
=> "#<Net::HTTPInternalServerError 500 Internal Server Error readbody=true>" 
ruby-1.9.2-p136 :006 > r.body 
=> "1 Errors:\r\nLine: 40 - ; expected" 
ruby-1.9.2-p136 :007 > 
7

在我看来,除非你需要一些真正的低级别的访问或控制,你最好使用Ruby的内置Open::URI模块:

require 'open-uri' 
io = open('http://www.example.org/') #=> #<StringIO:0x0000010103e240> 
body = io.read[0, 50] #=> "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Trans" 
io.status #=> ["200", "OK"] 
io.base_uri #=> #<URI::HTTP:0x00000100bf2ad8 URL:http://www.iana.org/domains/example/> 

注意的base_uri输出是不同的来自我传入的URL。Open :: URI跟随重定向,Net :: HTTP不会这样做。如果你在你的代码中抛出大量的随机URL并且不想编写重定向处理程序,这可以节省大量的时间。