patrick patrick - 1 year ago 137
iOS Question

NSMutableURLRequest with gzip encoding not working

I cannot seem to get NSUrlRequest to make use of gzipped server responses...

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"localhost:12345/content"]];

[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];

[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *connectionError) {
NSLog(@"data size: %i", [data length]);

==> data size: 226854

As you can see, if I do a curl with no Accept-encoding header, I get that same size:

% curl -s -w \%{size_download} -o /dev/null -H "Content-Type: application/json" -H "Accept: application/json" localhost:12345/content


Yet with a header for gzip, I get:

% curl -s -w \%{size_download} -o /dev/null -H "Content-Type: application/json" -H "Accept: application/json" -H "Accept-Encoding: gzip" localhost:12345/content


What am I doing wrong? How can I get my iOS app to properly make use of that gzip header?

Answer Source

The NSData that is passed to your completion handler is the data after it has been unzipped, so naturally you see the larger size.

The gzip encoding was used for the transfer and then NSURLConnection unzipped it and gave you the data; the zipped data wouldn't be much use to you, since you would just need to unzip it yourself. The point of gzip encoding is that it is transparent to your application but reduces network traffic.

There is no way to see the zipped data using NSURLConnection.

You could use a network capture tool, such as Wireshark, to capture the transfer and verify that gzip encoding was used.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download