如何通过HTTP下载只有ruby的大文件 [英] How to download via HTTP only piece of big file with ruby

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

问题描述

我只需要通过HTTP下载文件的前几千字节。

I only need to download the first few kilobytes of a file via HTTP.

我试过

require 'open-uri'
url = 'http://example.com/big-file.dat'
file = open(url)
content = file.read(limit)

但它实际上下载了整个文件。

But it actually downloads the full file.

推荐答案

这在使用套接字时似乎有效:

This seems to work when using sockets:

require 'socket'                  
host = "download.thinkbroadband.com"                 
path = "/1GB.zip" # get 1gb sample file
request = "GET #{path} HTTP/1.0\r\n\r\n"
socket = TCPSocket.open(host,80) 
socket.print(request)        

# find beginning of response body
buffer = ""                    
while !buffer.match("\r\n\r\n") do
  buffer += socket.read(1)  
end           

response = socket.read(100) #read first 100 bytes of body
puts response

我很好奇是否有红宝石方式。

I'm curious if there is a "ruby way".

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

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