红宝石 – 加载网页时:“undefined方法`request_uri’for#”

前端之家收集整理的这篇文章主要介绍了红宝石 – 加载网页时:“undefined方法`request_uri’for#”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用Ruby加载HTTP的网页,并检查其状态码是什么.我的代码如下所示:
require "net/http"
  @r = Net::HTTP.get_response(URI.parse(myURL))
  return @r.code

然而,对于一些URL(大多数是指向诸如Web计数器的奇怪的东西,不会给出适当的响应)我得到一个未定义的方法request_uri for#exception.我已经追溯到http.rb的第380行(我正在运行Ruby 1.8),它说:

def HTTP.get_response(uri_or_host,path = nil,port = nil,&block)
  if path
    host = uri_or_host
    new(host,port || HTTP.default_port).start {|http|
      return http.request_get(path,&block)
    }
  else
    uri = uri_or_host
    new(uri.host,uri.port).start {|http|
      return http.request_get(uri.request_uri,&block) <--- LINE 380
    }
  end
end

导致这个异常的原因我很失落.我会期望一个URI :: InvalidURIError,但不是这样.

解决方法

给定一个认可的方案(例如http / https),一个更专业的类将被实例化.否则创建“通用”URI; “请求URI”的想法只对某些URI方案有意义.

例:

irb(main):001:0> require 'uri'
=> true
irb(main):002:0> URI.parse('http://www.google.com/').class
=> URI::HTTP
irb(main):003:0> URI.parse('https://www.google.com/').class
=> URI::HTTPS
irb(main):004:0> URI.parse('foo://www.google.com/').class
=> URI::Generic
irb(main):005:0> URI.parse('http://www.google.com/').respond_to?(:request_uri)
=> true
irb(main):006:0> URI.parse('https://www.google.com/').respond_to?(:request_uri)
=> true
irb(main):007:0> URI.parse('foo://www.google.com/').respond_to?(:request_uri)
=> false

所以您解析的URI之一有一个奇怪的方案 – 即使它是一个有效的URI – 这就是全部.

猜你在找的HTML相关文章