如何在使用 Ruby 的 OpenUri 下载之前获取 HTTP 标头 [英] How to get HTTP headers before downloading with Ruby's OpenUri
问题描述
我目前正在使用 OpenURI 在 Ruby 中下载文件.不幸的是,如果不下载完整文件,似乎不可能获得 HTTP 标头:
I am currently using OpenURI to download a file in Ruby. Unfortunately, it seems impossible to get the HTTP headers without downloading the full file:
open(base_url,
:content_length_proc => lambda {|t|
if t && 0 < t
pbar = ProgressBar.create(:total => t)
end
},
:progress_proc => lambda {|s|
pbar.progress = s if pbar
}) {|io|
puts io.size
puts io.meta['content-disposition']
}
运行上面的代码表明它首先下载完整的文件,然后才打印我需要的标题.
Running the code above shows that it first downloads the full file and only then prints the header I need.
有没有办法在下载完整文件之前获取标题,所以如果标题不是我期望的那样,我可以取消下载?
Is there a way to get the headers before the full file is downloaded, so I can cancel the download if the headers are not what I expect them to be?
推荐答案
我想要的似乎无法使用 OpenURI 进行归档,至少不是,正如我所说,如果不先加载整个文件.
It seems what I wanted is not possible to archieve using OpenURI, at least not, as I said, without loading the whole file first.
我能够使用 Net::HTTP 的 request_get
I was able to do what I wanted using Net::HTTP's request_get
这里是一个例子:
http.request_get('/largefile.jpg') {|response|
if (response['content-length'] < max_length)
response.read_body do |str| # read body now
# save to file
end
end
}
请注意,这仅在使用块时有效,如下所示:
Note that this only works when using a block, doing it like:
response = http.request_get('/largefile.jpg')
正文已经被读取.
这篇关于如何在使用 Ruby 的 OpenUri 下载之前获取 HTTP 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!