封装:如图,AFNetWorking是封装在NSURL上层的网络接口封装。他在OC面向对象的基础上又封装了一次。
注意:
AFHTTPRequestOperationManager -- 对NSURLConnection的封装(3.0版本已经去掉NSURLConnection了)
AFHTTPSessionManager -- 对NSURLSession的封装
源码中默认的解析方式:可以自己设置。
PS:AFJSONResponseSerializer类中添加:@"text/plain",否者服务器返回数据这种类型无法解析
self.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"application/json", @"text/json", @"text/javascript", nil];
self.requestSerializer = [AFHTTPRequestSerializer serializer]; self.responseSerializer = [AFJSONResponseSerializer serializer];
3.AFHTTPRequestOperationManager 使用:默认
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; 请求参数 NSMutableDictionary *params = @{@“user”:@"czw" @"pwd":@"wtf"}; 发送请求 POST NSString *url = @"http://localhost:8080/czw/login"; [mgr POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { // 请求成功的时候回调 NSLog(@"success:%@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"failure"); }]; GET请求 [mgr GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { // 请求成功的时候回调 NSLog(@"success:%@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"failure"); }];
3.AFHTTPSessionManager使用
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager]; mgr.responseSerializer = [AFHTTPResponseSerializer serializer]; NSString *url = @"http://localhost:8080/czw/login"; [mgr GET:url parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { NSLog(@"success:%@", responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"failure"); }];
如果要详细的控制可以使用 代理方法
AFHTTPSessionManager:(他的代理方法很强大)
NSURLSessionDelegate,
NSURLSessionTaskDelegate,
NSURLSessionDataDelegate,
NSURLSessionDownloadDelegate