我有一个web服务类(MyAPIClient),它扩展了AFHTTPClient。对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编码。正如常见问题所说:
只需将HTTPBody从NSMutableURLRequest中取出,压缩数据,并在使用请求创建操作之前重新设置它。
我有戈兹帕图书馆这样我就能压缩数据了。接下来,我认为我需要重写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中编码并设置正确的“内容类型”,对吗?任何帮助都将不胜感激。
发布于 2013-08-06 14:10:25
如果有人有同样的问题,下面是我的解决方案(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];
}https://stackoverflow.com/questions/18064237
复制相似问题