通过 Net::HTTP 下载 zip 文件 [英] Download a zip file through Net::HTTP

查看:52
本文介绍了通过 Net::HTTP 下载 zip 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Net::HTTP 从 WordPress.org 下载 latest.zip.这是我到目前为止所得到的:

I am trying to download the latest.zip from WordPress.org using Net::HTTP. This is what I have got so far:

Net::HTTP.start("wordpress.org/") { |http|
  resp = http.get("latest.zip")
  open("a.zip", "wb") { |file| 
    file.write(resp.body)
  }
  puts "WordPress downloaded"
}

但这只会给我一个 4 KB 的 404 错误 HTML 页面(如果我将文件更改为 a.txt).我认为这与 URL 可能以某种方式重定向有关,但我不知道我在做什么.我是 Ruby 的新手.

But this only gives me a 4 kilobytes 404 error HTML-page (if I change file to a.txt). I am thinking this has something to do with the URL probably is redirected somehow but I have no clue what I am doing. I am a newbie to Ruby.

推荐答案

NET::HTTP 没有提供跟踪重定向的好方法,这里是一段我已经使用了一段时间的代码:

NET::HTTP doesn't provide a nice way of following redirects, here is a piece of code that I've been using for a while now:

require 'net/http'
class RedirectFollower
  class TooManyRedirects < StandardError; end

  attr_accessor :url, :body, :redirect_limit, :response

  def initialize(url, limit=5)
    @url, @redirect_limit = url, limit
  end

  def resolve
    raise TooManyRedirects if redirect_limit < 0

    self.response = Net::HTTP.get_response(URI.parse(url))

    if response.kind_of?(Net::HTTPRedirection)      
      self.url = redirect_url
      self.redirect_limit -= 1

      resolve
    end

    self.body = response.body
    self
  end

  def redirect_url
    if response['location'].nil?
      response.body.match(/<a href=\"([^>]+)\">/i)[1]
    else
      response['location']
    end
  end
end



wordpress = RedirectFollower.new('http://wordpress.org/latest.zip').resolve
puts wordpress.url
File.open("latest.zip", "w") do |file|
  file.write wordpress.body
end

这篇关于通过 Net::HTTP 下载 zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆