zoukankan      html  css  js  c++  java
  • iOS开发网络学习七:NSURLSession的基本使用get和post请求

    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        [self post];
    }
    
    -(void)get
    {
        //1.确定URL
        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
        
        //2.创建请求对象
        NSURLRequest *request =[NSURLRequest requestWithURL:url];
        
        //3.创建会话对象
        NSURLSession *session = [NSURLSession sharedSession];
        
        //4.创建Task
        /*
         第一个参数:请求对象
         第二个参数:completionHandler 当请求完成之后调用
            data:响应体信息
            response:响应头信息
            error:错误信息当请求失败的时候 error有值
         */
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            //6.解析数据
            NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        }];
        
        //5.执行Task
        [dataTask resume];
    }
    
    -(void)get2
    {
        //1.确定URL
        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
        
        //2.创建请求对象
        //NSURLRequest *request =[NSURLRequest requestWithURL:url];
        
        //3.创建会话对象
        NSURLSession *session = [NSURLSession sharedSession];
        
        //4.创建Task
        /*
         第一个参数:请求路径
         第二个参数:completionHandler 当请求完成之后调用
         data:响应体信息
         response:响应头信息
         error:错误信息当请求失败的时候 error有值
         注意:dataTaskWithURL 内部会自动的将请求路径作为参数创建一个请求对象(GET)
         */
        NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            //6.解析数据
            NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        }];
        
        //5.执行Task
        [dataTask resume];
    }
    
    -(void)post
    {
        //1.确定URL
        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
        
        //2.创建请求对象
        NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
        
        //2.1 设置请求方法为post
        request.HTTPMethod = @"POST";
        
        //2.2 设置请求体
        request.HTTPBody = [@"username=520it&pwd=520it&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
        
        //3.创建会话对象
        NSURLSession *session = [NSURLSession sharedSession];
        
        //4.创建Task
        /*
         第一个参数:请求对象
         第二个参数:completionHandler 当请求完成之后调用 !!! 在子线程中调用
         data:响应体信息
         response:响应头信息
         error:错误信息当请求失败的时候 error有值
         */
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            NSLog(@"%@",[NSThread currentThread]);
            //6.解析数据
            NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        }];
        
        //5.执行Task
        [dataTask resume];
    }
    
    @end

    #####2 NSURLSession的基本使用

    (1)使用步骤

            使用NSURLSession创建task,然后执行task

    (2)关于task

            a.NSURLSessionTask是一个抽象类,本身不能使用,只能使用它的子类

            b.NSURLSessionDataTaskNSURLSessionUploadTaskNSURLSessionDownloadTask

    (3)发送get请求

    ```objc

        //1.创建NSURLSession对象(可以获取单例对象)

        NSURLSession *session = [NSURLSession sharedSession];

        //2.根据NSURLSession对象创建一个Task

        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=ss&pwd=ss&type=JSON"];

        NSURLRequest *request = [NSURLRequest requestWithURL:url];

        //方法参数说明

        /*

        注意:该block是在子线程中调用的,如果拿到数据之后要做一些UI刷新操作,那么需要回到主线程刷新

        第一个参数:需要发送的请求对象

        block:当请求结束拿到服务器响应的数据时调用block

        block-NSData:该请求的响应体

        block-NSURLResponse:存放本次请求的响应信息,响应头,真实类型为NSHTTPURLResponse

        block-NSErroe:请求错误信息

         */

       NSURLSessionDataTask * dataTask =  [session dataTaskWithRequest:request completionHandler:^(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error) {

            //拿到响应头信息

            NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;

            //4.解析拿到的响应数据

            NSLog(@"%@ %@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding],res.allHeaderFields);

        }];

        //3.执行Task

        //注意:刚创建出来的task默认是挂起状态的,需要调用该方法来启动任务(执行任务)

        [dataTask resume];

    ```

    (4)发送get请求的第二种方式

    ```objc

      //注意:该方法内部默认会把URL对象包装成一个NSURLRequest对象(默认是GET请求)

        //方法参数说明

        /*

        //第一个参数:发送请求的URL地址

        //block:当请求结束拿到服务器响应的数据时调用block

        //block-NSData:该请求的响应体

        //block-NSURLResponse:存放本次请求的响应信息,响应头,真实类型为NSHTTPURLResponse

        //block-NSErroe:请求错误信息

         */

    - (nullable NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;

    ```

    (5)发送POST请求

    ```objc

            //1.创建NSURLSession对象(可以获取单例对象)

        NSURLSession *session = [NSURLSession sharedSession];

        //2.根据NSURLSession对象创建一个Task

        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];

        //创建一个请求对象,并这是请求方法为POST,把参数放在请求体中传递

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

        request.HTTPMethod = @"POST";

        request.HTTPBody = [@"username=520it&pwd=520it&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];

        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error) {

            //拿到响应头信息

            NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;

            //解析拿到的响应数据

            NSLog(@"%@ %@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding],res.allHeaderFields);

        }];

        //3.执行Task

        //注意:刚创建出来的task默认是挂起状态的,需要调用该方法来启动任务(执行任务)

        [dataTask resume];

    ```

    ---

  • 相关阅读:
    LOJ
    LOJ
    LOJ
    一种树形背包的时间复杂度证明
    [机器学习]第四、五周记录
    [机器学习]第三周记录
    [家里训练20_02_16]C
    [机器学习]第二周记录
    wireshark无响应的问题
    [机器学习]第一周记录
  • 原文地址:https://www.cnblogs.com/cqb-learner/p/5862428.html
Copyright © 2011-2022 走看看