Zlib::GzipFile::Error: not in gzip format

Zlib::GzipFile::Error: not in gzip format

我正在尝试用 zlibjruby 解码 gzip 字符串。这是最小的工作示例。

require 'stringio'
require 'zlib'

str = 'H4sIAAAAAAAA/y2NwQrDIBAFfyXstUbWNWrir5RSrEoQUi2JOZSQf6+EHt8wzDtgKd7VVPIG9n7AMwWwYhj1MBkkwtEwcN7vq/NfsAo5MnhFt6Y8g71WcDXW9I5ggVCYHqlH0xE12RJ1N5SIwGBpJ3UPTVOKa41IssGS5z+Vhhs1SdHo9okxXPXzcf4AY45Ve6EAAAA='
input = StringIO.new(str)
puts Zlib::GzipReader.new(input).read

这是我得到的输出

/Users/duke/.rvm/rubies/jruby-1.7.23/bin/jruby --1.9 -e $stdout.sync=true;$stderr.sync=true;load([=11=]=ARGV.shift) /Users/duke/RubymineProjects/untitled/gzip_test.rb
Zlib::GzipFile::Error: not in gzip format
  initialize at org/jruby/ext/zlib/JZlibRubyGzipReader.java:156
         new at org/jruby/ext/zlib/JZlibRubyGzipReader.java:85
      (root) at /Users/duke/RubymineProjects/untitled/gzip_test.rb:6
        load at org/jruby/RubyKernel.java:1059
      (root) at -e:1

Process finished with exit code 1

压缩后的字符串有效。你可以在这里试试 http://www.txtwizard.net/compression

您的 str 包含 Base64 编码数据。但是,由于 Zlib::GzipReader 不会自行解码数据,而是需要原始二进制 gzip 数据,因此失败。

您可以在创建 StringIO 对象之前手动解码数据:

require 'base64'
require 'stringio'
require 'zlib'

str = 'H4sIAAAAAAAA/y2NwQrDIBAFfyXstUbWNWrir5RSrEoQUi2JOZSQf6+EHt8wzDtgKd7VVPIG9n7AMwWwYhj1MBkkwtEwcN7vq/NfsAo5MnhFt6Y8g71WcDXW9I5ggVCYHqlH0xE12RJ1N5SIwGBpJ3UPTVOKa41IssGS5z+Vhhs1SdHo9okxXPXzcf4AY45Ve6EAAAA='
raw = Base64.decode64(str)
input = StringIO.new(raw)
puts Zlib::GzipReader.new(input).read
# => {"locations":[{"_id":1486497022087,"accuracy":50.0,"bearing":0.0,"datetime":"2017-02-07 22:50:22 +0300","latitude":55.660023,"longitude":37.759313,"speed":0.0}]}

您链接到的网站也描述了这种行为(强调我的):

This simple online text compression tool is compressing a plain text and decompressing compressed base64 string with gzip, bzip2 and deflate algorithms