gpt4 book ai didi

ios - AFHTTPClient 和 gzip

转载 作者:行者123 更新时间:2023-11-29 13:08:12 26 4
gpt4 key购买 nike

我有一个扩展 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说:

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

我得到了 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”,对吗?任何帮助,将不胜感激。

最佳答案

如果有人有同样的问题,这是我的解决方案(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];
}

关于ios - AFHTTPClient 和 gzip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18064237/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com