如何读取HEAD请求的http状态代码



我请求使用AFNetworking 4.3.1和Http方法的APIGETHEAD。它可以返回不同的http状态代码(100200402,..(

我的get功能请求运行良好。

-(void) getApiV2:(NSString *)url
parameters:(NSDictionary *)param
success:(successBlock)mSuccessBlock
failure:(failureBlock)mfailureBlock{
NSMutableDictionary *httpHeader =[NSMutableDictionary dictionary];
if(TOKEN !=nil){
[httpHeader setObject:TOKEN forKey:@"Token"];
}
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager
GET:url
parameters:param
headers:httpHeader
progress:nil
success: ^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
int statusCode = [[responseObject objectForKey:@"code"] intValue];
NSArray *data = [responseObject objectForKey:@"data"];
BLOCK_SAFE_RUN(mSuccessBlock,data,statusCode);
}
failure: ^(NSURLSessionDataTask * dataTask, NSError * error){
BLOCK_SAFE_RUN(mfailureBlock,error);
}
];
};

但是我的函数抛出错误。

-(void) head:(NSString *)url success:(successBlock)mSuccessBlock failure:(failureBlock)mfailureBlock{
NSMutableDictionary *httpHeader =[NSMutableDictionary dictionary];
if(TOKEN !=nil){
[httpHeader setObject:TOKEN forKey:@"Token"];
}
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager
HEAD:url
parameters:nil
headers:httpHeader
success: ^(id _Nullable responseObject){
int statusCode = [[responseObject objectForKey:@"code"] intValue];
BLOCK_SAFE_RUN(mSuccessBlock,responseObject,statusCode);
}
failure: ^(NSURLSessionDataTask * dataTask, NSError * error){
BLOCK_SAFE_RUN(mfailureBlock,error);
}
];
};

在运行时,我在int statusCode = [[responseObject objectForKey:@"code"] intValue];线上出现此错误

[__NSCFLocalDataTask objectForKey:]:无法识别的选择器发送到实例0x110f88860

服务器正确处理请求并完成它的工作。


我尝试其他语法:

int statusCode = (int) [responseObject statusCode];

"NSInvalidArgumentException",原因:"-[__NSCFLocalDataTask statusCode]:无法识别的选择器发送到实例0x145731af0">

来自SO

NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)responseObject;
int statusCode = (int) httpResponse.statusCode;

[__NSCFLocalDataTask statusCode]:无法识别的选择器发送到实例0x129665ed0


使用AFNetworking获取HEAD请求的http状态代码的好方法是什么?

根据@Larme的建议并经AFNetworking源代码确认,HEAD:parameters:headers:success:failure:返回一个NSURLSessionDataTask

所以我需要先检索NSHTTPURLResponse,然后才能获得statusCode

NSURLSessionTask *task = (NSURLSessionTask *)responseObject;
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)[task response];
int statusCode = (int) httpResponse.statusCode;
NSLog(@"Status code: %d", statusCode);

相关内容

  • 没有找到相关文章

最新更新