如何通过 HTTP 下载二进制文件? [英] How do I download a binary file over HTTP?

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

问题描述

如何使用 Ruby 通过 HTTP 下载和保存二进制文件?

How do I download and save a binary file over HTTP using Ruby?

网址是http://somedomain.net/flv/sample/sample.flv.

我使用的是 Windows 平台,我不想运行任何外部程序.

I am on the Windows platform and I would prefer not to run any external program.

推荐答案

最简单的方法是针对特定平台的解决方案:

The simplest way is the platform-specific solution:

 #!/usr/bin/env ruby
`wget http://somedomain.net/flv/sample/sample.flv`

可能您正在搜索:

require 'net/http'
# Must be somedomain.net instead of somedomain.net/, otherwise, it will throw exception.
Net::HTTP.start("somedomain.net") do |http|
    resp = http.get("/flv/sample/sample.flv")
    open("sample.flv", "wb") do |file|
        file.write(resp.body)
    end
end
puts "Done."

已更改.谢谢.

Edit2:下载时保存部分文件的解决方案:

The solution which saves part of a file while downloading:

# instead of http.get
f = open('sample.flv')
begin
    http.request_get('/sample.flv') do |resp|
        resp.read_body do |segment|
            f.write(segment)
        end
    end
ensure
    f.close()
end

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

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