网络请求返回的各种状态码
网络请求
+ (void)be_baseRequestModel:(BEBaseRequestModel *)model url:(NSString *)url finishBlock:(FinishBlcok)finishBlock
{
NSLog(@"请求URL = %@",url);
NSLog(@"requestDict = %@",model.keyValues);
NSString *utf = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", nil];
[manager GET:utf parameters:model.keyValues progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"responseObject = %@",responseObject);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
finishBlock(responseObject,nil);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error = %@",error);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
finishBlock(nil,error);
[self showError:error.localizedDescription];
}];
}
AFHTTPSessionManager.m
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
success:(void (^)(NSURLSessionDataTask *, id))success
failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
if (serializationError) {
if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
#pragma clang diagnostic pop
}
return nil;
}
__block NSURLSessionDataTask *dataTask = nil;
dataTask = [self dataTaskWithRequest:request
uploadProgress:uploadProgress
downloadProgress:downloadProgress
completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
//强转为NSHTTPURLResponse类型
NSHTTPURLResponse *obj = (NSHTTPURLResponse *)response;
//获取所以的statusCode
if (obj.statusCode!=200) {
[[NSNotificationCenter defaultCenter]postNotificationName:@"FailueCode" object:[NSString stringWithFormat:@"%ld",obj.statusCode]];
return ;
}
if (error) {
if (failure) {
failure(dataTask, error);
}
} else {
if (success) {
success(dataTask, responseObject);
}
}
}];
return dataTask;
}