29

如果网站返回“503 服务不可用”错误,则 open-uri 会引发异常。例如:

require 'open-uri'
open('http://www.google.co.uk/sorry/?continue=http://www.google.co.uk/search%3Fq%3Dhello%26oq%3Dhello%26ie%3DUTF-8')
# OpenURI::HTTPError: 503 Service Unavailable
# ...

但是,如果您随后在网络浏览器中访问它,它实际上会显示一个带有验证码而不是错误的页面。

如何确保 open-uri 不只是将其作为异常抛出,而是实际处理响应并为我提供页面内容?

4

1 回答 1

54

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; ...
于 2013-09-05T11:38:40.557 回答