美文网首页iOS DeveloperiOS 开发
NSURLConnection和NSURLSession

NSURLConnection和NSURLSession

作者: 張贺 | 来源:发表于2016-08-09 19:04 被阅读258次
    图片来自500px

    文 || 張贺

    NSURLConnection

    NSURLConnection的基本使用

    • 利用NSURLConnection进行网络请求分为3步:
    1. 创建请求路径(NSURL)
    2. 创建请求对象(NSURLRequest)
    3. 发送请求(NSURLConnection)
    发送同步请求
    • 使用sendSynchronousRequest: returningResponse: error:方法发送一个同步请求,该方法是阻塞式的会卡住线程。
      //1.创建请求路径
      NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=XML"];
      //2.创建请求对象
      NSURLRequest *request = [NSURLRequest requestWithURL:url];
      //3.发送请求
      NSURLResponse *response = nil;
      NSError error = nil;
      /

      发送同步请求,阻塞式的方法,会卡住线程

       request  : 请求对象
       response : 响应信息,当该方法执行完毕之后,该参数被赋值
       error    : 错误信息,如果请求失败,则error有值
       **/
      NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
      
      NSLog(@"%@",response);
      //解析服务器返回的数据
      NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
      NSLog(@"%@",dataStr);
      
    发送异步请求
    • 使用sendAsynchronousRequest: queue: completionHandler:方法发送一个异步请求。
      //1.创建请求路径
      NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=XML"];
      //2.创建请求对象
      NSURLRequest request = [NSURLRequest requestWithURL:url];
      //3.发送请求
      /

      发送异步请求

       request              : 请求对象
       queue                : 回调方法在哪个线程中执行,如果是主队列则block在主线程中执行,非主队列则在子线程中执行
       completionHandler    : 接受到响应的时候执行该block中的代码
                              response:响应头信息
                              data:响应体
                              connectionError:错误信息,如果请求失败,那么该参数有值
       **/
      
      [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
          NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
          NSLog(@"%@",dataStr);
        
      }];
      
    通过设置代理发送异步请求
    • 步骤:
      01 、确定请求路径
      02 、创建请求对象
      03 、创建NSURLConnection对象并设置代理
      04 、遵守NSURLConnectionDataDelegate协议,并实现相应的代理方法
      05 、在代理方法中监听网络请求的响应
    设置代理的3种方法
    • 通过
      [[NSURLConnection alloc]initWithRequest:request delegate:self];设置代理,通过这种方式设置代理将自动发送网络请求。请求回来的结果在代理方法中拿到。
    • 通过
      [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];这种方法设置代理,当startImmediately设置为YES时自动发送网络请求,当startImmediately设置为NO时,需手动调用- (void)start方法发送网络请求。
    • 通过
      使用类方法connectionWithRequest: delegate:设置代理,会自动发送网络请求。可以通过条用- (void)cancel;方法取消网络请求。
    相关的代理方法
    /*
     1.当接收到服务器响应的时候调用
     第一个参数connection:监听的是哪个NSURLConnection对象
     第二个参数response:接收到的服务器返回的响应头信息
     */
    - (void)connection:(nonnull NSURLConnection *)connection       
            didReceiveResponse:(nonnull NSURLResponse *)response
    
    /*
     2.当接收到数据的时候调用,该方法会被调用多次
     第一个参数connection:监听的是哪个NSURLConnection对象
     第二个参数data:本次接收到的服务端返回的二进制数据(可能是片段)
     */
    - (void)connection:(nonnull NSURLConnection *)connection 
            didReceiveData:(nonnull NSData *)data
    /*
    
     3.当服务端返回的数据接收完毕之后会调用
     通常在该方法中解析服务器返回的数据
     */
    -(void)connectionDidFinishLoading:(nonnull NSURLConnection *)connection
    
    /*4.当请求错误的时候调用(比如请求超时)
     第一个参数connection:NSURLConnection对象
     第二个参数:网络请求的错误信息,如果请求失败,则error有值
     */
    - (void)connection:(nonnull NSURLConnection *)connection 
            didFailWithError:(nonnull NSError *)error
    
    发送POST请求
    • 需要改变请求对象(NSMutableURLRequest)的请求方法(HTTPMethod)以及设置请求体(HTTPBody)等。注意:这里需要使用可变的请求对象。

      //1.创建请求路径
      NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
      //2.创建可变请求对象
      NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
      //更改请求方法
      request.HTTPMethod = @"POST";
      //设置具体的请求体
      request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
      //请求超时
      request.timeoutInterval = 5;
      //设置请求头
      [request setValue:@"ios 9.0" forHTTPHeaderField:@"User-Agent"];
      //3.发送请求
      /*
       发送异步请求
      
       request              : 请求对象
       queue                : 回调方法在哪个线程中执行,如果是主队列则block在主线程中执行,非主队列则在子线程中执行
       completionHandler    : 接受到响应的时候执行该block中的代码
                              response:响应头信息
                              data:响应体
                              connectionError:错误信息,如果请求失败,那么该参数有值
       **/
      
      [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
          //4.解析服务器返回的数据
          if (connectionError) {
              NSLog(@"--请求失败-");
          }else
          {
              NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
          }
      }];
      
    小结

    苹果官方在iOS9以后已经弃用了NSURLConnection,取而代之的是更为强大的NSURLSession。

    NSURLSession

    NSURLSession的基本使用

    • 使用步骤:使用NSURLSession对象创建Task,然后执行Task
    • Task的类型:
    Task类继承图
    • UIURLSessionTask是基类,要使用他的子类
    NSURLSessionDataTask基本使用
    • 通过dataTaskWithRequest: completionHandler:方法发送get/post请求
      //1.创建请求路径
      NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=XML"];
      //2.创建可变请求对象
      NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
      //如果是post请求,
      //更改请求方法
      //request.HTTPMethod = @"POST";
      //设置具体的请求体
      //request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];

      //3.创建NSURLSession
      NSURLSession *session = [NSURLSession sharedSession];
      
      //根据session对象来创建task
      /*
       request:请求对象
       completionHandler    : 接受到响应的时候执行该block中的代码
       response:响应头信息
       data:响应体
       error:错误信息,如果请求失败,那么该参数有值
       **/
      NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
          //这里的方法是在子线程内执行的
          NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
          NSLog(@"%@",dataStr);
      }];
      
      //默认创建出来task是暂停状态,需要手动启动
      [dataTask resume];
      
    • 通过dataTaskWithURL: completionHandler:方法发送只能发送GET请求
      //1.创建请求路径
      NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=XML"];

      //2.创建NSURLSession
      NSURLSession *session = [NSURLSession sharedSession];
      
      //根据session对象来创建task
      /*
      
       url:内部会自动把url包装成一个请求对象,是get请求,如果是post请求就不能用这个方法了
       completionHandler    : 接受到响应的时候执行该block中的代码
       response:响应头信息
       data:响应体
       error:错误信息,如果请求失败,那么该参数有值
      
       **/
      NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
          NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
          NSLog(@"%@",dataStr);
        
      }];
      
      //默认创建出来task是暂停状态,需要手动启动
      [dataTask resume];
      
    • 通过代理
      //1.创建请求路径
      NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=XML"];

      //创建NSURLSession,并设置代理
      /*
       configuration:配置信息
       delegate:代理
       queue:控制代理方法在哪个线程调用
       **/
      NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
      
      //创建task
      NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url];
      
      //默认创建出来task是暂停状态,需要手动启动
      [dataTask resume];
      
    • 代理方法
      #pragma mark 代理方法
      //接收到服务器响应的时候调用
      -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{

          /*
           NSURLSessionResponseCancel
           NSURLSessionResponseAllowcontinue
           NSURLSessionResponseBecomeDownload
           NSURLSessionResponseBecomeStream
           **/
      
          //当接收到服务器响应的时候,选择要不要接收服务器返回的数据
          completionHandler(NSURLSessionResponseAllow);
      
      }
      //接收到服务器返回的数据的时候调用,该方法可能会被调用多次
      -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
          NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
          NSLog(@"%@",dataStr);
      }
      
      //当请求完成之后调用,如果错误,那么error有值
      -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
      
      }

    相关文章

      网友评论

        本文标题:NSURLConnection和NSURLSession

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