簡體   English   中英

為什么在Net :: HTTP.get_response中的content_length有時即使為良好結果也為零?

[英]why is content_length in Net::HTTP.get_response sometimes nil even on good results?

我有以下紅寶石代碼(試圖寫一個簡單的http-ping)

require 'net/http'
res1 = Net::HTTP.get_response 'www.google.com' , '/'
res2 = Net::HTTP.get_response 'www.google.com' , '/search?q=abc'

res1.code #200
res2.code #200
res1.content_length #5213
res2.content_length #nil **<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< WHY**
res2.body[0..60]
=> "<!doctype html><html itemscope=\"\" itemtype=\"http://schema.org"

為什么res2 content_length無法顯示? 它是否在res2的其他屬性中(如何看到它們?)

我是紅寶石的新手。 在AWS Linux上使用irb 0.9.6

非常感謝。

看起來,返回的值不一定是主體的長度,而是內容的固定長度(當該固定長度預先已知並存儲在content-length標頭中時)。

請參閱HTTPHeader#content_length的實現源(取自http://ruby-doc.org/stdlib-2.3.1/libdoc/net/http/rdoc/Net/HTTPHeader.html ):

# File net/http/header.rb, line 262
def content_length
  return nil unless key?('Content-Length')
  len = self['Content-Length'].slice(/\d+/) or
      raise Net::HTTPHeaderSyntaxError, 'wrong Content-Length format'
  len.to_i
end

在這種情況下,這可能意味着該響應是一個多部分的MIME響應,並且在這種情況下未使用content-length標頭。

在這種情況下,您最可能需要的是body.length ,因為這是告訴多部分響應的響應主體實際長度的唯一真實方法。

注意,始終使用content.body查找內容長度可能會對性能產生影響; 您可以選擇先嘗試使用content_length方法,如果沒有,則退回到body.length

這是對代碼的示例修改:

require 'net/http'
res1 = Net::HTTP.get_response 'www.google.com' , '/'
res2 = Net::HTTP.get_response 'www.google.com' , '/search?q=abc'

res1.code #200
res2.code #200
res1.content_length #5213
res2.content_length.nil? ? res2.body.length : res2.content_length #57315  **<<<<<<<<<<<<<<< Works now **
res2.body[0..60]
=> "<!doctype html><html itemscope=\"\" itemtype=\"http://schema.org"

或者更好的是,捕獲content_length並將捕獲的值用於比較:

res2_content_length = res2.content_length

if res2_content_length.nil?
    res2_content_length = res2.body.length
end

就個人而言,我總是堅持檢查body.length並在出現問題時處理任何潛在的性能問題。

無論您是否收到多部分響應的簡單響應,這都應該為您可靠地檢索內容的實際長度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM