• OC HTTPRequest GET和POST请求的代码封装


    对于GET和PSOT请求我们在开发中会经常使用,所以对代码进行封装就可以做到事半功倍.下面就介绍下怎么对代码进行封装,

    要求是:

     1.要有网络成功和失败的blcok.

     2.如果服务器传回的是 JSON 数据,自动解析;如果不是,直接返回二进制数据.

     3.默认成功之后的block回调在主线程进行.

    首先我们要创建一个类ZSNetworkTool,继承自NSObject,代码如下

    #import <Foundation/Foundation.h>

    //定义别名

    //成功回调类型:参数: 1. id: object(如果是 JSON ,那么直接解析成OC中的数组或者字典.如果不是JSON ,直接返回 NSData)

    typedef void(^SuccessBlock)(id object , NSURLResponse *response);

    // 失败回调类型:参数: NSError error;

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

     @interface ZSNetworkTool : NSObject

    // 单例的实例化方法

    + (instancetype)sharedNewtWorkTool;

    // GET请求调用的方法 其中: urlString:网络接口. paramaters:参数字典 参数字典:  key:服务器接收参数的 key 值.  value:参数内容. 成功回调类型:参数: 1. id: object(如果是 JSON ,那么直接解析成OC中的数组或者字典.如果不是JSON ,直接返回 NSData) 2. NSURLResponse: response ,  success: 成功回调. fail 失败回调.

    - (void)GETRequestWithUrl:(NSString *)urlString paramaters:(NSMutableDictionary *)paramaters successBlock:(SuccessBlock)success FailBlock:(failBlock)fail;

    // POST请求调用方法 其中: urlString:网络接口. paramaters:参数字典 参数字典:  key:服务器接收参数的 key 值.  value:参数内容. 成功回调类型:参数: 1. id: object(如果是 JSON ,那么直接解析成OC中的数组或者字典.如果不是JSON ,直接返回 NSData) 2. NSURLResponse: response ,  success: 成功回调. fail 失败回调.

    -(void)POSTRequestWithUrl:(NSString *)urlString paramaters:(NSMutableDictionary *)paramaters successBlock:(SuccessBlock)success FailBlock:(failBlock)fail;

     @end

     //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    在.m实现方法

    #import "ZSNetworkTool.h"

    @implementation ZSNetworkTool

    // 单例的实例化方法

    +(instancetype)sharedNewtWorkTool

    {

        static id _instance;

       static dispatch_once_t onceToken;

        dispatch_once(&onceToken, ^{

            _instance = [[self alloc] init];

        });

        return _instance;

    }

     //实现GET请求方法

    - (void)GETRequestWithUrl:(NSString *)urlString paramaters:(NSMutableDictionary *)paramaters successBlock:(SuccessBlock)success FailBlock:(failBlock)fail

    {

        NSMutableString *strM = [[NSMutableString alloc] init];

    //遍历参数字典将value和key拼装在一起

         [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];

    }

    //POST请求方法

    - (void)POSTRequestWithUrl:(NSString *)urlString paramaters:(NSMutableDictionary *)paramaters successBlock:(SuccessBlock)success FailBlock:(failBlock)fail

    {

        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];

        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) {

            // 网络请求成功:

            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方法

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

    {

        NSLog(@"touchesBegan");

        NSMutableDictionary *dict = @{@"username":@"value1",@"password":@"value2"}.mutableCopy;

        [[CZNetworkTool sharedNewtWorkTool] GETRequestWithUrl:@"http://127.0.0.1/login/login.php" paramaters:dict successBlock:^(id object, NSURLResponse *response) {

              NSLog(@"网络请求成功:%@ %@",object,[NSThread currentThread]);

        } FailBlock:^(NSError *error) {

                NSLog(@"网络请求失败");

        }];

       }

    @end

  • 相关阅读:
    AOP第一个例子
    初学Spring
    MyBatis延迟加载,缓存的使用
    MyBatis关联查询
    MyBatis的基本操作(02)-----Seeeion.commit引起事务的提交,多条件查询,智能标签的应用,ResultMap结果映射
    Js练习题之查找字符串中出现最多的字符和个数
    Js练习题之字符串转驼峰
    Js笔试题之正则表达式
    Js笔试题之千分位格式化
    Js笔试题之parseInt()和.map()
  • 原文地址:https://www.cnblogs.com/relly0121/p/5277755.html
Copyright © 2020-2023  润新知