Objective-c – How to send HTTP POST request with gziped content

gziphttphttp-postiphoneobjective c

I'm developing iPhone app and manually constructing POST requests. Currently, need to compress JSON data before sending it, so looking how to tell a server the content is compressed. Setting content type header to gzip might be not acceptable because server expects JSON data. I'm looking for transparent solution, something like just to add some header telling JSON data is compressed into gzip.

I know, the standard way is to tell the server that the client accepts encoding, but you need to make GET request with accept encoding header first. In my case, I want to post the data already encoded.

Best Answer

Include a Obj-C gzip wrapper, for example NSData+GZip, and use it to encode the body of your NSURLRequest. Also remember to set the Content-Encoding accordingly, so the webserver will know how to treat your request.

NSData *requestBodyData = [yourData gzippedData];
NSString *postLength = [NSString stringWithFormat:@"%d", requestBodyData.length];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
[request setHTTPBody:requestBodyData];