【问题标题】:If open-uri works, why does net/http return an empty string?如果 open-uri 有效,为什么 net/http 返回一个空字符串?
【发布时间】:2015-07-24 10:15:19
【问题描述】:

我正在尝试从 Wikipedia 下载一个页面。对于这样的任务,我正在使用宝石。当使用 net/http 时,我得到的只是一个空字符串。所以我尝试了 open-uri 并且效果很好。

不过,我更喜欢第一个选项,因为它给了我更明确的控制;但为什么它返回一个空字符串?

class Downloader
    attr_accessor :entry, :url, :page

    def initialize
        # require 'net/http'
        require 'open-uri'
    end

    def getEntry
        print "Article name? "
        @entry = gets.chomp
    end

    def getURL(entry)

        if entry.include?(" ")
            @url = "http://en.wikipedia.org/wiki/" + entry.gsub!(/\s/, "_")
        else
            @url = "http://en.wikipedia.org/wiki/" + entry
        end
        @url.downcase!
    end

    def getPage(url)

=begin THIS FAULTY SOLUTION RETURNS AN EMPTY STRING ???
        connector = URI.parse(url)
        connection = Net::HTTP.start(connector.host, connector.port) do |http|
            http.get(connector.path)
        end
        puts "Body:"
        @page = connection.body
=end

        @page = open(url).read
    end

end

test = Downloader.new
test.getEntry
test.getURL(test.entry)
test.getPage(test.url)
puts test.page

P.S.:我是一名自学成才的程序员,所以代码可能不适合好的做法。我很抱歉。

【问题讨论】:

  • 不知道,我得到了正确的身体。 (顺便说一句,您不必检查 entry 是否包含空格;gsub 很乐意将零空格更改为零下划线。您不应该在参数上使用 gsub!,除非它是该方法的目的 -意想不到的后果等等。不要在initialize 中要求,除非您有特殊理由,否则文件顶部通常更清晰。)

标签: ruby-on-rails ruby net-http open-uri


【解决方案1】:

由于您的请求返回 301 Redirect(检查 connection.code 值),如果您使用 net/http,则应手动执行重定向。 Here 更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2013-10-22
    • 2021-10-09
    相关资源
    最近更新 更多