开发者

Optimized way of getting the size of a response in Ruby?

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜