Ruby Net :: HTTP not decrypting gzip?

I have ruby-1.9.3-p327 with zlib installed. localhost:80 is a simple nginx test page.

 require "net/http" => true Net::HTTP::HAVE_ZLIB => true res = Net::HTTP.start("localhost", "80") do |http| req = Net::HTTP::Get.new "/" req["accept-encoding"] = "gzip" http.request req end => #<Net::HTTPOK 200 OK readbody=true> res.get_fields "content-encoding" => ["gzip"] res.body => "\x1F\x8B\b\x00\x00\x00\x00\x00\x00\x03\xEC\xBDi..." 

The body was not decoded. Why?

+4
source share
4 answers

If you use http.get , it should automatically decode it, but it looks like request may not do this for you.

There is clearly code to unpack the gzip request, but only for the get method: https://github.com/ruby/ruby/blob/v1_9_3_327/lib/net/http.rb#L1031

+5
source

For those who have a problem with code that runs on ruby ​​1.9 and does not work when upgrading to ruby ​​2.0, just include this code in your project.

 module HTTPResponseDecodeContentOverride def initialize(h,c,m) super(h,c,m) @decode_content = true end def body res = super if self['content-length'] self['content-length']= res.bytesize end res end end module Net class HTTPResponse prepend HTTPResponseDecodeContentOverride end end 
+9
source

Based on my experiments, at least one reason for this is due to the right_http_connection gem. I tested versions 1.3.0 and 1.4.0. This gem monkey fixes Net :: HTTP and causes problems with decoding GZipped responses.

You can learn more about this issue in this GitHub issue .

+3
source

I think he does not do this automatically.

To decode, try the following code snippet (assuming the answer is StringIO):

 begin Zlib::GzipReader.new(response).read rescue Zlib::GzipFile::Error, Zlib::Error # Not gzipped response.rewind response.read end 
+1
source

Source: https://habr.com/ru/post/1446210/


All Articles