In a recent task, you need to obtain an XML file from the network, but the file is compressed using gzip. Some people say that you can decompress gzip with URLRequest, but this must be indicated by the accept-encoding in the header returned by the server. That is to say, you can use this sentence to achieve self-decompression:
[URLRequest addvalue: @ "gzip" forhttpheaderfield: @ "Accept-encoding"];
This does not work in my project because the header returned by the server does not have an Accept-encoding description. This requires manual decompression! Decompress the package and import the libz.1.2.3.dylib library. Import # import "zlib. H"
The following is the decompressed code:
-(Nsdata *) uncompresszippeddata :( nsdata *) compresseddata
{
If ([compresseddata length] = 0) return compresseddata;
Unsigned full_length = [compresseddata length];
Unsigned half_length = [compresseddata length]/2;
Nsmutabledata * decompressed = [nsmutabledata datawithlength: full_length + half_length];
Bool done = no;
Int status;
Z_stream STRM;
STRM. next_in = (bytef *) [compresseddata bytes];
STRM. avail_in = [compresseddata length];
STRM. total_out = 0;
STRM. zarloc = z_null;
STRM. zfree = z_null;
If (inflateinit2 (& STRM, (15 + 32 ))! = Z_ OK) return nil;
While (! Done ){
// Make sure we have enough room and reset the lengths.
If (STRM. total_out> = [decompressed length]) {
[Decompressed increaselengthby: half_length];
}
STRM. next_out = [decompressed mutablebytes] + STRM. total_out;
STRM. avail_out = [decompressed length]-STRM. total_out;
// Inflate another chunk.
Status = inflate (& STRM, z_sync_flush );
If (status = z_stream_end ){
Done = yes;
} Else if (status! = Z_ OK ){
Break;
}
}
If (inflateend (& STRM )! = Z_ OK) return nil;
// Set real length.
If (done ){
[Decompressed setlength: STRM. total_out];
Return [nsdata datawithdata: decompressed];
} Else {
Return nil;
}
}
The above is a method that can be easily searched on the Internet. It is correct, but there is a problem, that is, zip mentioned in the original article, which makes it easy to think that zip can also be decompressed. However, after verification, this method cannot decompress the ZIP file. Decompress the GZIP file.
Mark it as follows: gzip and ZIP files are not as simple as an extension, and there is a big difference in the compression algorithm. It's just that a lot of compression software has been shielded, so people don't feel their difference.