2010-02-18 69 views
14

我试图使用Ruby通过HTTP加载网页并检查其状态码是什么。我的代码如下所示:加载网页时:“undefined method`request_uri'为#”

require "net/http" 
    @r = Net::HTTP.get_response(URI.parse(myURL)) 
    return @r.code 

然而,对于某些URL(主要是那些指着如网站计数器,将无法给出正确的响应奇怪的东西),我发现了一个undefined method request_uri for #例外。我追查回线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,但不是这样。

+1

这不是一个答案,所以我把它作为评论发布。我在将Rails 3.0应用程序转换为Rails 3.1应用程序时遇到了以下错误:session [:return_to] = request.request_uri – Docunext 2011-09-10 14:28:38

回答

26

给定一个公认的方案(例如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 - 这一切。

+0

哦,哈哈,检查request_uri方法是否存在时我在错误的文档页面上。 – Matchu 2010-02-18 21:27:35

+0

单线程应该适用于大多数类型的URI:'uri.try(:request_uri)|| uri.to_s'(如果对象不响应该消息,则尝试返回nil) – gmcnaughton 2016-11-02 12:16:54

0

首先,至于为什么它是#,我的猜测是这个错误出现在浏览器中,因此被认为是HTML。尝试查看源代码并查看它是否不是#<ObjectWhatever>

至于错误,这听起来是正确的。这仅表示您正在使用的URI对象没有request_uri方法。也许你打算使用path