【问题标题】:How to decompress http?如何解压http?
【发布时间】:2016-07-03 11:50:52
【问题描述】:

我正在尝试读取包含 http 压缩消息的 tcp 数据包,但它失败并出现“zlib 解压缩期间的异常:( -3 ) 不正确的标头检查”。我的代码有什么问题,或者是否有一个库可以为我做到这一点?

std::string decompress_string(const std::string& str) {
    z_stream zs;                        // z_stream is zlib's control structure
    memset(&zs, 0, sizeof(zs));

    if (inflateInit(&zs) != Z_OK)
        throw(std::runtime_error("inflateInit failed while decompressing."));

    zs.next_in = (Bytef*)str.data();
    zs.avail_in = str.size();

    int ret;
    char outbuffer[32768];
    std::string outstring;

    // get the decompressed bytes blockwise using repeated calls to inflate
    do {
        zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
        zs.avail_out = sizeof(outbuffer);

        ret = inflate(&zs, 0);

        if (outstring.size() < zs.total_out) {
            outstring.append(outbuffer,
                             zs.total_out - outstring.size());
        }

    } while (ret == Z_OK);

    inflateEnd(&zs);

    if (ret != Z_STREAM_END) {          // an error occurred that was not EOF
        qDebug()  << "Exception during zlib decompression: (" << ret << ") " << zs.msg;
        return "";
    }

    return outstring;
}

std::string parseHttp(std::string payload) {
    size_t index = payload.find("\r\n\r\n");
    if (index == std::string::npos) {
        qDebug() << "http body not found, dropped.";
        return "";
    }
    std::string body = payload.substr(index + 4);
    if (payload.find("Content-Encoding: gzip") == std::string::npos){
        return body;
    } else {
        return decompress_string(body);
    }
}

【问题讨论】:

  • 这里的答案有帮助吗:ZLib Inflate() failing with -3 Z_DATA_ERROR
  • 好吧,也许,我不确定我是否完全理解,但如果我只是将 inflate(&zs, 0) 替换为 inflateInit2(&zs, -MAX_WBITS),它仍然不起作用。跨度>

标签: c++ qt http zlib


【解决方案1】:

它可能是 gzip 格式。尝试使用inflateInit2() 并将wbits 设置为31 来解码gzip 格式。 gzip 数据以1f 8b 08 开头。

【讨论】:

  • 所以基本上用 inflateInit2(&zs, -MAX_WBITS) 替换 inflate(&zs, 0) ?正如我在评论中所说的那样,这就是我试图做的,但它不起作用
  • 叹息。我儿子在阅读理解方面也有同样的问题。我没有说-MAX_WBITS。我说31
  • 我也试过替换 ret = inflate(&zs, 0); by ret = inflateInit2(&zs, 31);,但它也不起作用,程序终止。我还检查了有效载荷的第一个字节确实是 1F 8B 08 00 00 00 00 00 00 00 BD。
  • 什么?不,您将 inflateInit(&amp;zs) 替换为 inflateInit2(&amp;zs, 31)。你不要用inflateInit2()替换inflate()
猜你喜欢
  • 2021-03-20
  • 2012-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多