zoukankan      html  css  js  c++  java
  • NSURLSession的GET和POST请求的封装

    简介:因为在iOS9.0之后,以前使用的NSURLConnection过期,苹果推荐使用NSURLSession来替换NSURLConnection完成网路请求相关操作。

    之前已经在  http://www.cnblogs.com/evening015/p/5317848.html  介绍如何使用NSURLSession来发送GET请求和POST请求。

    这里会将其封装起来,方便以后可以通过一个方法实现所有过程。

    基本思路:

      1.创建一个继承自NSObject的自定义类,用来调用封装的POST和GET方法

      2.在自定义类里面创建单例对象创建方法:

    +(instancetype)sharedNewtWorkTool
    {
        static id _instance;
        
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [[self alloc] init];
        });
        return _instance;
    }
    创建单例对象方法

      3.封装方法参数说明:

          (1)urlString:登录接口字符串

         (2)paramaters:请求参数字典   key:服务器提供的接收参数的key. value:参数内容

         (3)typedef void(^SuccessBlock)(id object , NSURLResponse *response):成功后回调的block :参数: 1. id: object(如果是 JSON ,那么直接解析     成OC中的数组或者字典.如果不是JSON ,直接返回 NSData) 2. NSURLResponse: 响应头信息,主要是对服务器端的描述

         (4)typedef void(^failBlock)(NSError *error):失败后回调的block:参数: 1.error:错误信息,如果请求失败,则error有值

      

    GET请求方法封装:

    -(void)GETRequestWithUrl:(NSString *)urlString paramaters:(NSMutableDictionary *)paramaters successBlock:(SuccessBlock)success FailBlock:(failBlock)fail
    {
        // 1. 创建请求.
        
        // 参数拼接.
        
        // 遍历参数字典,一一取出参数,按照参数格式拼接在 url 后面.
        
        NSMutableString *strM = [[NSMutableString alloc] init];
        
        [paramaters enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            
            // 服务器接收参数的 key 值.
            NSString *paramaterKey = key;
            
            // 参数内容
            NSString *paramaterValue = obj;
            
            // appendFormat :可变字符串直接拼接的方法!
            [strM appendFormat:@"%@=%@&",paramaterKey,paramaterValue];
        }];
        
        urlString = [NSString stringWithFormat:@"%@?%@",urlString,strM];
        
        // 截取字符串的方法!
        urlString = [urlString substringToIndex:urlString.length - 1];
        
        NSLog(@"urlString:%@",urlString);
        
        NSURL *url = [NSURL URLWithString:urlString];
        
        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
        
        // 2. 发送网络请求.
        // completionHandler: 说明网络请求完成!
        [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            
            NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            
            
            // 网络请求成功:
            if (data && !error) {
                
                // 查看 data 是否是 JSON 数据.
                
                // JSON 解析.
                id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
                
                // 如果 obj 能够解析,说明就是 JSON
                if (!obj) {
                    obj = data;
                }
                
                // 成功回调
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    if (success) {
                        success(obj,response);
                    }
                });
                
            }else //失败
            {
                // 失败回调
                if (fail) {
                    fail(error);
                }
            }
            
        }] resume];
    }
    GET请求方法封装:

     POST请求方法封装:

    -(void)POSTRequestWithUrl:(NSString *)urlString paramaters:(NSMutableDictionary *)paramaters successBlock:(SuccessBlock)success FailBlock:(failBlock)fail
    {
        // 1. 创建请求.
        
        // 参数拼接.
        // 遍历参数字典,一一取出参数
        
        NSMutableString *strM = [[NSMutableString alloc] init];
        
        [paramaters enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            
            // 服务器接收参数的 key 值.
            NSString *paramaterKey = key;
            
            // 参数内容
            NSString *paramaterValue = obj;
            
            // appendFormat :可变字符串直接拼接的方法!
            [strM appendFormat:@"%@=%@&",paramaterKey,paramaterValue];
        }];
        
        NSString *body = [strM substringToIndex:strM.length - 1];
        
        NSLog(@"%@",body);
        
        NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];
        
        NSURL *url = [NSURL URLWithString:urlString];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
        
        // 1.设置请求方法:
        request.HTTPMethod = @"POST";
        
        // 2.设置请求体
        request.HTTPBody = bodyData;
        
        // 2. 发送网络请求.
        // completionHandler: 说明网络请求完成!
        [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            
            NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            
            
            // 网络请求成功:
            if (data && !error) {
                
                // 查看 data 是否是 JSON 数据.
                
                // JSON 解析.
                id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
                
                // 如果 obj 能够解析,说明就是 JSON
                if (!obj) {
                    obj = data;
                }
                
                // 成功回调
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    if (success) {
                        success(obj,response);
                    }
                });
                
            }else //失败
            {
                // 失败回调
                if (fail) {
                    fail(error);
                }
            }
            
        }] resume];
    
    }
    POST请求方法的封装

    自定义类算是粗略的完成了,接下来就是检验成果的时候:

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        NSLog(@"touchesBegan");
        
        //创建参数字典
        NSMutableDictionary *dict = @{@"username":@"zhangsan",@"password":@"zhang"}.mutableCopy;
        
        // 一句话发送 GET 请求.
        [[CZNetworkTool sharedNewtWorkTool] GETRequestWithUrl:@"http://127.0.0.1/login/login.php" paramaters:dict successBlock:^(id object, NSURLResponse *response) {
            
            NSLog(@"网络请求成功:%@",object);
            
        } FailBlock:^(NSError *error) {
    
            NSLog(@"网络请求失败");
            
        }];
       
    }
    一句话发送 GET 请求.
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        NSLog(@"touchesBegan");
        
        //创建参数字典
        NSMutableDictionary *dict = @{@"username":@"zhangsan",@"password":@"zhang"}.mutableCopy;
        
        // 一句话发送 GET 请求.
        [[CZNetworkTool sharedNewtWorkTool] POSTRequestWithUrl:@"http://127.0.0.1/login/login.php" paramaters:dict successBlock:^(id object, NSURLResponse *response) {
            
            NSLog(@"网络请求成功:%@",object);
            
        } FailBlock:^(NSError *error) {
    
            NSLog(@"网络请求失败");
            
        }];
       
    }
    一句话发送POST请求

    代码执行结果:

    成功!

          

         

  • 相关阅读:
    创建文件夹 文件File操作方法
    C#WinForm4张纸牌窗体设计
    b/s结构和c/s结构
    sql 中 时间只显示日期
    视图
    js获取字符串的字节数
    触发器
    将xml字符串转换成dataset
    sql 集合查询 数据更新操作语句
    带有ANY(SOME)或ALL谓词的字查询
  • 原文地址:https://www.cnblogs.com/evening015/p/5321673.html
Copyright © 2011-2022 走看看