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

Lan*_*ard 1 ruby http file

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

Ark*_*kku 10

调用.size你写入tempfile的东西?

或者如果它通过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
Run Code Online (Sandbox Code Playgroud)

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