AFHTTPClient and gzip

1.6k views Asked by At

I have a web service class (MyAPIClient) that extends AFHTTPClient. All request to a web server are send using postPath method and the data is in JSON format. MyAPIClient contains only one method:

- (id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    [self setDefaultHeader:@"Accept" value:@"application/json"];
    [self setParameterEncoding:AFJSONParameterEncoding];
    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];   

    return self;
}

Now I want to add gzip encoding. As the FAQ says:

Simply take the HTTPBody from a NSMutableURLRequest, compress the data, and re-set it before creating the operation using the request.

I got the Godzippa library so I can compress data. Next I think I need to override postPath method, something like this:

-(void)postPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure
{
    NSMutableURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters];
    NSData *newData = [[request HTTPBody] dataByGZipCompressingWithError:nil];    
    [request setHTTPBody:newData];

    [self setDefaultHeader:@"Content-Type" value:@"application/gzip"];

    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self enqueueHTTPRequestOperation:operation];

}

I believe this is not the right way to do it as the AFHTTPClient needs to convert NSDictionary to JSON and only then I can encode in gzip and set the right "Content-Type", right? Any help would be appreciated.

1

There are 1 answers

0
sash On

If someone has the same problem, here is my solution (Godzippa didn't work for me, so I used different library to encode data):

- (id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    [self setDefaultHeader:@"Content-Type" value:@"application/json"];
    [self setDefaultHeader:@"Content-Encoding" value:@"gzip"];
    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];

    return self;
}

-(void)postPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure
{
    NSData *newData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:NULL];
    newData = [newData  gzipDeflate];

    NSMutableURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:nil];    
    [request setHTTPBody:newData];

    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self enqueueHTTPRequestOperation:operation];
}