AFNetworking使用

//Get请求数据

+ (void)get:(NSString *)urlStr params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure

{

        // 1.获得请求管理者

        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

        NSString *URL = [NSString stringWithFormat:@"%@%@",HOST,urlStr];

        NSLog(@"%@",URL);

        // 2.发送GET请求

        [mgr GET:URL parameters:params

        success:^(AFHTTPRequestOperation *operation, id responseObj) {

            if (success) {

                success(responseObj);

            }

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            if (failure) {

                failure(error);

            }

        }];

}

 

//Post请求数据

+ (void)post:(NSString *)urlStr params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure

{

    if ([[self class] checkNetworkState]) {

        //获取公用参数

        NSMutableDictionary *requestParms = [[self class] publicParms];

        if (params!=nil) {

            //不为空 合并字典,公共参数字典

            [requestParms addEntriesFromDictionary:params];

        }

        //1.获得请求管理者

        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

    /********这里很重要********/

        //1.mgr.responseSerializer = [AFJSONResponseSerializer serializer];

        //2.mgr.requestSerializer = [AFJSONRequestSerializer serializer];

        //3.mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];

 

        NSString *URL = [NSString stringWithFormat:@"%@%@",HOST,urlStr];

        NSLog(@"当前接口URL==%@",URL);

        NSLog(@"当前接请求的 参数 ==%@",requestParms);

        // 2.发送POST请求

        [mgr POST:URL parameters:requestParms success:^(AFHTTPRequestOperation *operation, id responseObj) {

            

            success(responseObj);

            

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            

            failure(error);

            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];

            NSLog(@"底层失败 ==error ==%@",[error localizedDescription]);

            [MBProgressHUD showError:@"网络不给力,稍后再试" toView:[UIApplication sharedApplication].keyWindow];

            

        }];

        

    }else{

        

        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];

        [MBProgressHUD showError:@"网络已断开,请检查网络连接" toView:[UIApplication sharedApplication].keyWindow];

        failure(nil);

        

    }

}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。