zoukankan      html  css  js  c++  java
  • iOS网络-NSURLConnection简单介绍

    GET请求

    同步请求(GET-SendSync)
    (1)步骤
        1 设置请求路径
        2 创建请求对象(默认是GET请求,且已经默认包含了请求头)
        3 使用NSURLSession sendsync方法发送网络请求
        4 接收到服务器的响应后,解析响应体

    (2)相关代码

    //1.确定请求路径
        //协议头+主机地址+接口名称+?+参数1&参数2&参数3
        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];    
        //2.创建请求对象|GET
        //默认已经包含了请求头|请求方法(GET)
        NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];  
        //3.发送请求(GET)
        //同步请求,会阻塞线程
        /*
         第一个参数:请求对象
         第二个参数:响应头
         第三个参数:错误信息
         返回值:NSData类型,响应体信息
         */
        NSError *error = nil;
        NSURLResponse *response = nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];  
        //4.解析数据
        if (error == nil) {
            NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
            NSLog(@"%@---%@",response,error);
        }

    异步请求(GET-SendAsync)

      (1)相关说明
         该方法不会卡住当前线程,网络请求任务是异步执行的

    (2)相关代码

        //1.确定请求路径
        //协议头+主机地址+接口名称+?+参数1&参数2&参数3
        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=888&pwd=520it&type=JSON"];   
        //2.创建请求对象|GET
        //默认已经包含了请求头|请求方法(GET)
        NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];    
        //3.发送异步请求
        /*
         第一个参数:请求对象
         第二个参数:队列,决定block在哪个线程调用
         第三个参数:completionHandler 当请求结束(成功|失败)的时候执行
            response:响应头
            data:响应体信息
         connectionError:错误信息
         */
        [NSURLConnection sendAs
    ynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:
    ^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { //4.解析数据 NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]); }];

    异步请求(GET-代理)
    (1)步骤
          1 确定请求路径
          2 创建请求对象
          3 创建NSURLConnection对象并设置代理
          4 遵守NSURLConnectionDataDelegate协议,并实现相应的代理方法
          5 在代理方法中监听网络请求的响应
    (2)设置代理的几种方法

    //1.确定请求路径
        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
        
        //2.创建请求对象
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        //3.设置代理
        //第一种方式,该方法会自动发送网络请求
       //NSURLConnection *connect =  [[NSURLConnection alloc]initWithRequest:request delegate:self];
        
         //第二种方式,同上
        //[NSURLConnection connectionWithRequest:request delegate:self];
        
        //第三种方法
        /*
         第一个参数:请求对象
         第二个参数:谁成为代理
         第三个参数:startImmediately :是否立即开始发送网络请求
         */
        NSURLConnection *connect = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
    [connect start];
    //[connect cancel]; 取消 #pragma mark - NSURLConnectionDataDelegate //1.当接受到服务器响应的时候会调用:response(响应头) -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { self.fileData = [NSMutableData data]; NSLog(@"didReceiveResponse"); } //2.当接受到服务器返回数据的时候调用(会调用多次) -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog(@"didReceiveData---%zd",data.length); //拼接数据 [self.fileData appendData:data]; } //3.当请求失败的时候调用 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"didFailWithError"); } //4.当请求结束(成功|失败)的时候调用 -(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"connectionDidFinishLoading"); //解析数据 NSLog(@"%@",[[NSString alloc]initWithData:self.fileData encoding:NSUTF8StringEncoding]); }

    POST请求

    (1)发送POST请求步骤

    a.确定URL路径
    b.创建请求对象(可变对象)
    c.修改请求对象的方法为POST,设置请求体(Data)
    d.发送一个异步请求
    e.补充:设置请求超时,处理错误信息,设置请求头(如获取客户端的版本等等,请求头是可设置可不设置的)

    (2)相关代码

        //1.确定请求路径
        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
        //2.创建请求对象
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        //2.1更改请求方法
        request.HTTPMethod = @"POST";
        //2.2设置请求体
        request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
        //2.3请求超时
        request.timeoutInterval = 5;
        //2.4设置请求头
        [request setValue:@"ios 9.0" forHTTPHeaderField:@"User-Agent"];
        //3.发送请求
        [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]);
            }
    
        }];
  • 相关阅读:
    最长公共子序列-动态规划
    归并排序
    最大子段和-3种方法
    kafka compaction 分析(基于kafka 0.10.2版本)
    [转载]interp1
    [转]mat2gray函数原理分析
    Java 位运算(移位、位与、或、异或、非)与逻辑运算
    ML01a
    [第1集] 机器学习的动机与应用
    tap4fun公司面试总结
  • 原文地址:https://www.cnblogs.com/liugengqun/p/5130382.html
Copyright © 2011-2022 走看看