如何在使用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屋!