利用zlib庫對HTTP收到的gzip資料解壓
阿新 • • 發佈:2019-01-01
1、首先說為什麼採用zlib解壓,因為zlib可以解壓記憶體資料。
2、下載zlib庫後,自己在projcts目錄裡面根據需要編譯lib庫
3、靜態連結只需要zlib.h ;zconf.h;zlib.lib三個檔案即可(動態的不介紹了)
4、解壓函式:
[html] view plain copy
- /* HTTP gzip decompress */
- int httpgzdecompress(Byte *zdata, uLong nzdata,
- Byte *data, uLong *ndata)
- {
- int err = 0;
- z_stream d_stream = { 0 }; /* decompression stream */
- static char dummy_head[2] =
- {
- 0x8 + 0x7 * 0x10,
- (((0x8 + 0x7 * 0x10) * 0x100 + 30) / 31 * 31) & 0xFF,
- };
- d_stream.zalloc = (alloc_func)0;
- d_stream.zfree = (free_func)0;
- d_stream.opaque = (voidpf)0;
- d_stream.next_in = zdata;
- d_stream.avail_in = 0;
- d_stream.next_out = data;
- //if (inflateInit2(&d_stream, -MAX_WBITS) != Z_OK) return -1;
- if (inflateInit2(&d_stream, 47) != Z_OK) return -1;
- while (d_stream.total_out < *ndata && d_stream.total_in < nzdata) {
- d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */
- if ((err = inflate(&d_stream, Z_NO_FLUSH)) == Z_STREAM_END) break;
- if (err != Z_OK)
- {
- if (err == Z_DATA_ERROR)
- {
- d_stream.next_in = (Bytef*)dummy_head;
- d_stream.avail_in = sizeof(dummy_head);
- if ((err = inflate(&d_stream, Z_NO_FLUSH)) != Z_OK)
- {
- return -1;
- }
- }
- else return -1;
- }
- }
- if (inflateEnd(&d_stream) != Z_OK) return -1;
- *ndata = d_stream.total_out;
- return 0;
- }
eg:
char* pDest = new char[1024 * 16];
uLong ulLength = 1024*16;
gzdecompress((Byte*)precvBuff, nCount, (Byte*)pDest, &ulLength);