我正在嘗試讀取包含http壓縮消息的tcp數據包,但它在'zlib解壓縮期間出現異常:(-3)不正確的頭部檢查'時失敗。我的代碼有什麼問題,還是有一個庫可以幫我嗎?如何解壓http?
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()失敗-3 Z_DATA_ERROR](http://stackoverflow.com/questions/18700656/zlib-inflate-failing-with-3-z-data-error) – kicken
也許,我不確定我是否理解這一切,但如果我只是用inflateInit2(&zs,-MAX_WBITS)替換inflate(&zs,0),它仍然不起作用。 – KevinFox