在Ruby中获取响应大小的优化方法?

我可以使用File.size(path)来获取文件的大小(以字节为单位)。 如何在不将其写入临时文件的情况下获取HTTP响应的大小?

在你写入tempfile的东西上调用.size

或者,如果它通过HTTP,您可能只能从标题中获取内容长度。 例:

 require 'net/http' response = nil # Just get headers Net::HTTP.start('stackoverflow.com', 80) do |http| response = http.head('/') end puts response.content_length # Get the entire response Net::HTTP.start('stackoverflow.com', 80) do |http| response = http.get('/') end puts response.body.size 

请注意,如果服务器未提供内容长度(通常是动态内容的情况),则response.content_length将为nil