【问题标题】:Net::HTTP returning 404 when I know it's 301当我知道它是 301 时,Net::HTTP 返回 404
【发布时间】:2012-10-05 12:39:55
【问题描述】:

我编写了一段 Ruby 代码,用于跟踪一系列潜在的重定向,直到到达最终 URL:

def self.obtain_final_url_in_chain url
  logger.debug "Following '#{url}'"
  uri = URI url
  http = Net::HTTP.start uri.host, uri.port
  response = http.request_head url 
  case response.code
  when "301"
    obtain_final_url_in_chain response['location']
  when "302"
    obtain_final_url_in_chain response['location']
  else
    url
  end
end

您使用 url 调用 obtain_final_url_in_chain,它最终应该返回最终 url。

我正在尝试使用此 URL:http://feeds.5by5.tv/master

基于 http://web-sniffer.net/,由于 301 重定向,这应该重定向到 http://5by5.tv/rss。相反,虽然我得到了 http://feeds.5by5.tv/master 的 404。

上述代码为其他 URL 返回 200(例如 http://feeds.feedburner.com/5by5video)。

请问有人知道为什么会这样吗?快把我逼疯了!

谢谢。

【问题讨论】:

    标签: ruby net-http


    【解决方案1】:

    根据docs for Net::HTTP#request_head,您要传递路径,而不是完整的url,作为第一个参数。

    有了这些和其他一些更改,这是重写方法的一种方法:

    def obtain_final_url_in_chain(url)
      uri = URI url
      response = Net::HTTP.start(uri.host, uri.port) do |http|
        http.request_head uri.path
      end
    
      case response
      when Net::HTTPRedirection
        obtain_final_url_in_chain response['location']
      else
        url
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2016-12-05
      • 2011-07-02
      • 2020-06-07
      • 1970-01-01
      • 2017-10-30
      • 2010-12-07
      • 2013-11-05
      • 1970-01-01
      相关资源
      最近更新 更多