2013-08-05 35 views
1

我有一個擴展AFHTTPClient的Web服務類(MyAPIClient)。所有對Web服務器的請求都使用postPath方法發送,並且數據採用JSON格式。 MyAPIClient只包含一種方法:AFHTTPClient和gzip

- (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說:使用請求創建操作之前

乾脆把HTTPBody從NSMutableURLRequest,壓縮 數據,並重新設置。

我得到了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」,對吧?任何幫助,將不勝感激。

回答

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]; 
}