File: body_decoding_handler.rb

package info (click to toggle)
libwww-mechanize-ruby 1.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 956 kB
  • ctags: 883
  • sloc: ruby: 6,621; makefile: 4
file content (48 lines) | stat: -rw-r--r-- 1,450 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Mechanize
  class Chain
    class BodyDecodingHandler
      include Mechanize::Handler

      def handle(ctx, options)
        body = options[:response_body]
        response = options[:response]

        options[:response_body] =
          if encoding = response['Content-Encoding']
            case encoding.downcase
            when 'gzip'
              Mechanize.log.debug('gunzip body') if Mechanize.log
              if response['Content-Length'].to_i > 0 || body.length > 0
                begin
                  Zlib::GzipReader.new(body).read
                rescue Zlib::BufError, Zlib::GzipFile::Error
                  if Mechanize.log
                    Mechanize.log.error('Caught a Zlib::BufError')
                  end
                  body.rewind
                  body.read(10)
                  Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate(body.read)
                rescue Zlib::DataError
                  if Mechanize.log
                    Mechanize.log.error("Caught a Zlib::DataError, unable to decode page: #{$!.to_s}")
                  end
                  ''
                end
              else
                ''
              end
            when 'x-gzip'
              body.read
            when '7bit'
              body.read
            else
              raise 'Unsupported content encoding'
            end
          else
            body.read
          end
        super
      end
    end
  end
end