【问题标题】:Mechanize::ResponseReadError - Content-Length does not match response body lengthMechanize::ResponseReadError - Content-Length 与响应正文长度不匹配
【发布时间】:2014-07-17 17:00:19
【问题描述】:

我在使用 Mechanize 请求页面时遇到了这个错误:

Mechanize::ResponseReadError
内容长度 (17317) 不匹配 响应正文长度 (17070) (Mechanize::ResponseReadError)

非常感谢您对为什么会发生这种情况以及如何解决它的任何想法!

【问题讨论】:

  • 能否截取响应并检查响应正文是否确实比 Content-Length 短?

标签: ruby-on-rails ruby ruby-on-rails-4 mechanize mechanize-ruby


【解决方案1】:

网站会返回错误的内容长度值。捕获错误并强制页面解析。

agent = Mechanize.new
begin
  page = agent.get 'http://bad.com'
rescue Mechanize::ResponseReadError => e
  page = e.force_parse
end

您也可以将 agent.ignore_bad_chunking 设置为 true — 但要注意可能的静默内容丢失。

【讨论】:

    【解决方案2】:

    这是因为Content-Length标头的大小不等于response-body长度的大小。

    查看mechanize gem 采用的以下规格。它会引发同样的错误。

      def test_response_read_content_length_mismatch
        def @res.content_length() 5 end
        def @res.read_body() yield 'part' end
    
        e = assert_raises Mechanize::ResponseReadError do
          @agent.response_read @res, @req, @uri
        end
    
        assert_equal 'Content-Length (5) does not match response body length (4)' \
          ' (Mechanize::ResponseReadError)', e.message
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      • 2011-11-06
      • 2018-02-22
      相关资源
      最近更新 更多