我有一个扩展AFHTTPClient的Web服务类(MyAPIClient)。对Web服务器的所有请求都使用postPath方法发送,数据采用JSON格式。 MyAPIClient只包含一种方法:
- (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;
}
现在我要添加gzip编码。正如FAQ所说:
只需从NSMutableURLRequest获取HTTPBody,压缩即可 数据,并在使用请求创建操作之前重新设置它。
我有Godzippa库,所以我可以压缩数据。接下来我想我需要覆盖postPath方法,如下所示:
-(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];
}
我认为这不是正确的方法,因为AFHTTPClient需要将NSDictionary转换为JSON,然后才能在gzip中编码并设置正确的“Content-Type”,对吧?任何帮助,将不胜感激。
答案 0 :(得分: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];
}