歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> NSURLSession的GET和POST請求的封裝

NSURLSession的GET和POST請求的封裝

日期:2017/3/1 9:17:19   编辑:Linux編程

簡介:因為在iOS9.0之後,以前使用的NSURLConnection過期,蘋果推薦使用NSURLSession來替換NSURLConnection完成網路請求相關操作。

之前已經在 http://www.linuxidc.com/Linux/2016-04/129797.htm 介紹如何使用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請求

代碼執行結果:

成功!

Copyright © Linux教程網 All Rights Reserved