Optimized way of getting the size of a response in

2019-04-15 07:16发布

I can do File.size(path) to get the size of a file in bytes. How do I get the size of an HTTP response without writing it to a tempfile?

标签: ruby http file
1条回答
倾城 Initia
2楼-- · 2019-04-15 07:42

Call .size on the thing you'd write to the tempfile?

Or if its over HTTP, you might be able to get the content length from headers alone. Example:

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

Note that if the server does not provide the content length (often the case for dynamic content), then response.content_length will be nil.

查看更多
登录 后发表回答