gpt4 book ai didi

ios - 如何使用AFHTTPSessionManager记录每个请求/响应?

转载 作者:行者123 更新时间:2023-12-01 17:39:51 33 4
gpt4 key购买 nike

我正在将项目迁移到AFNetworking 2.0。使用AFNetworking 1.0时,我编写了代码来记录控制台中的每个请求/响应。这是代码:

-(AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(AFHTTPRequestOperation *, id))success
failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure
{
AFHTTPRequestOperation *operation =
[super HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject){
[self logOperation:operation];
success(operation, responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
failure(operation, error);
}];

return operation;
}

-(void)logOperation:(AFHTTPRequestOperation *)operation {

NSLog(@"Request URL-> %@\n\nRequest Body-> %@\n\nResponse [%d]\n%@\n%@\n\n\n",
operation.request.URL.absoluteString,
[[NSString alloc] initWithData:operation.request.HTTPBody encoding:NSUTF8StringEncoding],
operation.response.statusCode, operation.response.allHeaderFields, operation.responseString);
}

我正在尝试使用AFNetworking 2.0做同样的事情,据我了解,这意味着使用 NSURLSessionDataTask对象而不是 AFHTTPRequestOperation。这是我的照片。
-(NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler {

NSURLSessionDataTask *task = [super dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error){

[self logTask:task];
completionHandler(response, responseObject, error);
}];

return task;
}

-(void)logTask:(NSURLSessionDataTask *)task {

NSString *requestString = task.originalRequest.URL.absoluteString;
NSString *responseString = task.response.URL.absoluteString;

NSLog(@"\n\nRequest - %@\n\nResponse - %@\n\n", requestString, responseString);
}
dataTaskWithRequest:completionHandler方法正在成功拦截每个调用,因此我认为这是重写的正确方法,但是当我尝试将任务记录在completionHandler中时, task为nil。从而在控制台中打印出空值。但是,仍然从该方法返回适当的任务对象。这里发生了什么事?如何正确记录每个 call 的请求/响应?

最佳答案

您可以使用库AFNetworking / AFNetworkActivityLogger

https://github.com/AFNetworking/AFNetworkActivityLogger

从文档:

AFNetworkActivityLogger是AFNetworking 2.0的扩展,可记录日志
发送和接收网络请求。

用法:

[[AFNetworkActivityLogger sharedLogger] startLogging];

输出:
GET http://example.com/foo/bar.json
200 http://example.com/foo/bar.json

使用开发日志记录级别,您也应该具有responseHeaderFields和responseString

关于ios - 如何使用AFHTTPSessionManager记录每个请求/响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23370325/

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