iOS afnetworking集中请求方式的封装

文章目录

    • block
        • 成功block回调
        • 失败block回调
    • GET
    • POST

block

成功block回调

typedef void(^DicBlock)(NSDictionary * dic);

失败block回调

typedef void(^ErrorBlock)(NSError * error);

GET

+(void)getHttp:(NSString *)url
 andparameters:(NSDictionary *)parameters
       success:(DicBlock)block
         error:(ErrorBlock)errblock;



+(void)getHttp:(NSString *)url andparameters:(NSDictionary *)parameters success:(DicBlock)block error:(ErrorBlock)errblock{
    
    //初始化manager
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //传json数据需设置
    AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
    [serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];


    manager.requestSerializer = serializer;
    manager.requestSerializer.timeoutInterval = 6.0f;//最长请求时长

    [manager GET:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        block(dic);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",[error localizedDescription]);
        errblock(error);

    }];
    
    
}

POST

+(void)postHttp:(NSString *)url
  andparameters:(NSDictionary *)parameters
        success:(DicBlock)block
          error:(ErrorBlock)errblock;



+(void)postHttp:(NSString *)url andparameters:(NSDictionary *)parameters success:(DicBlock)block error:(ErrorBlock)errblock{
    
    
    
    //初始化manager
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //传json数据需设置
    AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
    [serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    manager.requestSerializer = serializer;
    manager.requestSerializer.timeoutInterval = 6.0f;

    [manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        block(dic);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",[error localizedDescription]);
        
        
        errblock(error);
    }];
    
    
}


你可能感兴趣的:(技术)