AFNetworking:PUT、Delete、Get、Post

作者: 青巷水彩 | 来源:发表于2016-12-13 19:55 被阅读5476次

    Put、Delete、Get、Post封装方法设置请求头
    还有获取用户权限以及登录请求的封装方法

    先是不常用的吧(写的时候不是)
    // GET超级api

    + (void)requestGETSuperAPIWithURLStr:(NSString *)urlStr WithAuthorization:(NSString *)authorization paramDic:(NSDictionary *)paramDic finish:(void(^)(id responseObject))finish enError:(void(^)(NSError *error))enError{
    
       AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
       manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"text/html",@"application/json",@"text/javascript",@"text/json",@"text/plain",@"charset=UTF-8", nil];
       
       // 设置请求头
       [manager.requestSerializer setValue:authorization forHTTPHeaderField:@"Authorization"];
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
       
       [manager GET:urlStr parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           // 成功回调
           finish(responseObject);
           // 如果superapikey过期,重新保存加密获取新的
           // 如果用户apikey过期,则重新登录
       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           // 失败回调
           enError(error);
           
       }];
    }
    

    // POST请求 立即登录

    + (void)requestLoginPOSTWithURLStr:(NSString *)urlStr WithAuthorization:(NSString *)authorization paramDic:(NSDictionary *)paramDic finish:(void(^)(id responseObject))finish enError:(void(^)(NSError *error))enError{
       
       AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
       
       manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"text/html",@"application/json",@"text/javascript",@"text/json",@"text/plain",@"charset=UTF-8", nil];
    
       // 设置请求头
       [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
       [manager.requestSerializer setValue:authorization forHTTPHeaderField:@"Authorization"];
       [manager POST:urlStr parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           
           NSString *errcode = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"errcode"]];
           if ([errcode isEqualToString:@"0"]) {
               finish(responseObject);
           }else {
               NSString *errmsg = [responseObject objectForKey:@"errmsg"];
           }
       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           // 失败回调
           enError(error);
       }];
    }
    

    pragma mark - 请求数据GET和POST PUT

    // GET 请求

    + (void)requestGETWithURLStr:(NSString *)urlStr paramDic:(NSDictionary *)paramDic Api_key:(NSString *)api_key finish:(void(^)(id responseObject))finish enError:(void(^)(NSError *error))enError{
       
       AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
       manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"text/html",@"application/json",@"text/javascript",@"text/json",@"text/plain",@"charset=UTF-8", nil];
       
       // 设置请求头
       [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
     
       [manager.requestSerializer setValue:api_key forHTTPHeaderField:@"api_key"];
      
       [manager GET:urlStr parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           
           NSString *errcode = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"errcode"]];
           
           if ([errcode isEqualToString:@"0"]) {
               finish(responseObject);  
           }else  {
               NSString *errmsg = [responseObject objectForKey:@"errmsg"];
           }
       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           enError(error);
       }];
    }
    

    // POST请求

    + (void)requestPOSTWithURLStr:(NSString *)urlStr paramDic:(NSDictionary *)paramDic Api_key:(NSString *)api_key finish:(void(^)(id responseObject))finish enError:(void(^)(NSError *error))enError{
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"text/html",@"application/json",@"text/javascript",@"text/json",@"text/plain",@"charset=UTF-8", nil];
        
        // 设置请求头
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [manager.requestSerializer setValue:api_key forHTTPHeaderField:@"api_key"];
        
        [manager POST:urlStr parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString *errcode = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"errcode"]];
            if ([errcode isEqualToString:@"0"]) {
                
                finish(responseObject);
            }else if ([errcode isEqualToString:@"100000"]) {
                NSString *errmsg = [responseObject objectForKey:@"errmsg"];
                // 弹出提示信息
                [[NetworkManager shareNetworkManager].mdelegate showMessage:errmsg];
            }else{
                NSString *errmsg = [responseObject objectForKey:@"errmsg"];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            enError(error);
        }];
        
    }
    

    pragma mark - PUT 请求

    + (void)requestPUTWithURLStr:(NSString *)urlStr paramDic:(NSDictionary *)paramDic Api_key:(NSString *)api_key finish:(void(^)(id responseObject))finish enError:(void(^)(NSError *error))enError{
    
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",@"text/javascript",@"text/json",@"text/plain", nil];
        
        // 设置请求头
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [manager.requestSerializer setValue:api_key forHTTPHeaderField:@"api_key"];
        [manager PUT:urlStr parameters:paramDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString *errcode = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"errcode"]];
            
            if ([errcode isEqualToString:@"0"]) {
                
                finish(responseObject);
                
            }else{
                NSString *errmsg = [responseObject objectForKey:@"errmsg"];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            enError(error);
        }];
    }
    

    //delete和put差不多,没有参数哦,记得里面的方法要改
    // 还有福利!
    // 上传图片

    + (void)requestAddImgPOSTWithURLStr:(NSString *)url paramDic:(NSDictionary *)paramDic image:(UIImage *)image name:(NSString *)name success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure{
        
        // 1.创建网络管理者
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"text/html",@"application/json",@"text/javascript",@"text/json",@"text/plain", nil];
        //请求图片,请求网页时需要加入这句,因为AFN默认的请求的是json
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        // 2.发送请求(字典只能放非文件参数)
        [manager POST:url parameters:paramDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            NSData *imageData = UIImageJPEGRepresentation(image, 0.5);//进行图片压缩
            // 使用日期生成图片名称
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
            
            // 上传图片,以文件流的格式
            // 任意的二进制数据MIMEType application/octet-stream
            // 特别注意,这里的图片的名字不要写错,必须是接口的图片的参数名字如我这里是file
            if (imageData!=nil) { // 图片数据不为空才传递
                [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/png"];
            } 
        } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
            if ([[dic objectForKey:@"status"]isEqualToString:@"success"]) {
                 success(responseObject);  
            }else{
                NSString *message = [responseObject objectForKey:@"message"];
                NSLog(@"messageImg == %@",message);
                 [[NetworkManager shareNetworkManager].mdelegate showMessage:message];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failure(error);
        }]; 
    }
    

    相关文章

      网友评论

      • 戒烟不戒酒:你用过 AFNetworking 的 PUT上传图片吗
        青巷水彩:@戒烟不戒酒 没有
      • 独爱ii: [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        这段代码干嘛用的,怎么设置两次请求头
      • 哈哈西:创建网络管理者的方法并不是单例
      • 哈哈西:这样封装网络请求方法,会有严重的内存泄露
        哈哈西:@大萌哥哥 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];创建网络管理者的方法并不是单例,你可以用这套封装方法多使用几个网络请求,然后用leak检测下就知道,内存泄漏的地方了。基本上都是AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];的问题。
        大萌哥哥:为啥啊?求详解
      • MoShi_New:put请求中的Api_key是指的什么?
        青巷水彩:@MoShi_New 可以这么说
        MoShi_New:@我就叫茵陈 也就是说你这个方法里面只是多了一个参数,去掉之后就是普通的put请求?
        青巷水彩:是我们接口中必须传的,来获取用户权限。要看接口配置
      • 北暖37:你好,我按照你写的方法进行post请求,但是每次都报错2017-01-05 20:27:20.755179 友店[2759:551130] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: URLString',崩溃地方在AFN的AFURLRequestSerialization,你遇到了么,有什么解决方法么
        青巷水彩:@慕糖123 :smile: 不客气~
        北暖37:@我就叫茵陈 谢谢,问题解决了,确实是传给后台的参数有问题。
        青巷水彩:@慕糖123 你的参数有问题

      本文标题:AFNetworking:PUT、Delete、Get、Post

      本文链接:https://www.haomeiwen.com/subject/kwubmttx.html