Ruby HTTP获取源代码和状态
我目前正在使用以下方法获取页面的源代码:Ruby HTTP获取源代码和状态,ruby,Ruby,我目前正在使用以下方法获取页面的源代码: Net::HTTP.get(URI.parse(page.url)) 我还希望获得HTTP状态,而无需发出第二个请求 有没有其他方法可以做到这一点?我一直在看文档,但似乎找不到我要找的内容。对不起,我已经找到了:) ruby-1.9.2-p136:004>r=Net::HTTP.get\u响应(URI.parse)http://badurlexample.com')) => # ruby-1.9.2-p136:005>r.inspect => "#
Net::HTTP.get(URI.parse(page.url))
我还希望获得HTTP状态,而无需发出第二个请求
有没有其他方法可以做到这一点?我一直在看文档,但似乎找不到我要找的内容。对不起,我已经找到了:)
ruby-1.9.2-p136:004>r=Net::HTTP.get\u响应(URI.parse)http://badurlexample.com'))
=> #
ruby-1.9.2-p136:005>r.inspect
=> "#"
ruby-1.9.2-p136:006>r.body
=>“1个错误:\r\n行:40-;应为”
ruby-1.9.2-p136:007>
在我看来,除非您需要真正的低级访问或控制,否则最好使用Ruby的内置模块:
需要“打开uri”
io=打开('http://www.example.org/') #=> #
body=io.读[0,50]#=>“[“200”,“OK”]
io.base_uri#=>#
请注意,base\u uri
的输出与我传入的URL不同。Open::uri会为您执行重定向,而Net::HTTP不会这样做。如果您在代码中抛出大量随机URL,并且不想编写重定向处理程序,那么这会带来很大的回报
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 >
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/>