OpenURI::HTTPError
有一个io
属性,你可以检查得到你想要的。io
是一个StringIO
定义了几个单例方法的对象(status
例如):
require 'open-uri'
begin
open('http://www.google.co.uk/sorry/?continue=http://www.google.co.uk/search%3Fq%3Dhello%26oq%3Dhello%26ie%3DUTF-8')
rescue OpenURI::HTTPError => error
response = error.io
response.status
# => ["503", "Service Unavailable"]
response.string
# => <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<html DIR=\"LTR\">\n<head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"><meta name=\"viewport\" content=\"initial-scale=1\">...
end
然而,对于这个任务,Net::HTTP
模块可能是一个更好的选择:
require 'net/http'
response = Net::HTTP.get_response(URI.parse('http://www.google.co.uk/sorry/?continue=http://www.google.co.uk/search%3Fq%3Dhello%26oq%3Dhello%26ie%3DUTF-8'))
response.code
# => "503"
response.body
# => "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<html DIR=\"LTR\">\n<head><meta http-equiv=\"content-type\" content=\"text/html; ...