1

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.

4

1 回答 1

1

如果有人有同样的问题,这是我的解决方案(Godzippa 对我不起作用,所以我使用不同的库来编码数据):

- (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];
}
于 2013-08-06T14:10:25.277 回答