zoukankan      html  css  js  c++  java
  • 网络第一节——NSURLConnection

    一、NSURLConnection的常用类

    (1)NSURL:请求地址

    (2)NSURLRequest:封装一个请求,保存发给服务器的全部数据,包括一个NSURL对象,请求方法、请求头、请求体....

    (3)NSMutableURLRequest:NSURLRequest的子类

    (4)NSURLConnection:负责发送请求,建立客户端和服务器的连接。发送NSURLRequest的数据给服务器,并收集来自服务器的响应数据

     

    二、NSURLConnection的使用

    1.简单说明

    使用NSURLConnection发送请求的步骤很简单

    (1)创建一个NSURL对象,设置请求路径(设置请求路径)

    (2)传入NSURL创建一个NSURLRequest对象,设置请求头和请求体(创建请求对象)

    (3)使用NSURLConnection发送NSURLRequest(发送请求)

    2.代码示例

    (1)发送请求的三个步骤:

        1.设置请求路径

        2.创建请求对象

        3.发送请求

            3.1发送同步请求(一直在等待服务器返回数据,这行代码会卡住,如果服务器,没有返回数据,那么在主线程UI会卡住不能继续执行操作)有返回值

            3.2发送异步请求:没有返回值

    说明:任何NSURLRequest默认都是get请求。

    (2)发送同步请求代码示例:

    #pragma mark- NSURLConnection同步发送请求

     

    - (void)sendRequestSync

    {

        //请求的地址

        NSURL *url = [[NSURL alloc] initWithString:@"http://aqicn.org/publishingdata/json"];

        //创建请求

        NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];

        // 发送同步请求, data就是返回的数据

        NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];

        if (data == nil) {

            NSLog(@"send request failed!");

        }

        

        NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

        

        NSDictionary *dic = [arr objectAtIndex:0];

        NSArray *arrNew = [dic objectForKey:@"pollutants"];

        NSDictionary *dicNew = [arrNew objectAtIndex:0];

        msgLable.text = [NSString stringWithFormat:@"污染源:%@,污染指数:%@",[dicNew objectForKey:@"pol"],[dicNew objectForKey:@"value"]];

    }

     

    (3)发送异步请求

    发送异步请求有两种方式:

    1)使用block回调

    2)代理

    A.使用block回调方法发送异步请求

    使用block回调代码示例

    #pragma mark- NSURLConnection异步发送请求block方式

     

    -(void) sendRequestAsyByBlock

    {

        //请求的地址

        NSURL *url = [[NSURL alloc] initWithString:@"http://aqicn.org/publishingdata/json"];

        //创建请求

        NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];

        

        //创建一个队列(默认添加到该队列中的任务异步执行)

        //NSOperationQueue *queue=[[NSOperationQueue alloc]init];

        

        //获取一个主队列

        NSOperationQueue *queue=[NSOperationQueue mainQueue];

        [NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)

        {

            NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

            

            NSDictionary *dic = [arr objectAtIndex:0];

            NSArray *arrNew = [dic objectForKey:@"pollutants"];

            NSDictionary *dicNew = [arrNew objectAtIndex:0];

            msgLable.text = [NSString stringWithFormat:@"污染源:%@,污染指数:%@",[dicNew objectForKey:@"pol"],[dicNew objectForKey:@"value"]];

        }];

     

     

    }

    补充一下post接口说明:

     NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://aqicn.org/publishingdata/json"]];

    //更改请求的方式
        req.HTTPMethod = @"POST";
        
        //上传给服务器的字符串
        NSString *postStr = @"cate_id=2729";
        NSLog(@"111%@",postStr);
        
        //POST上传的数据一般都需要转换成二进制
        NSData *postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"%@",postData);
        
        //设置请求主体内容body
        request.HTTPBody = postData;

     [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {      
            if (connectionError) {      
                NSLog(@"connectionError = %@",connectionError);          
            }else{         
                NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]);           
            }

    代码说明:

    block代码段:当服务器有返回数据的时候调用会开一条新的线程去发送请求,主线程继续往下走,当拿到服务器的返回数据的数据的时候再回调block,执行block代码段。这种情况不会卡住主线程。

    队列的作用:决定这个block操作放在哪个线程执行?

    刷新UI界面的操作应该放在主线程执行,不能放在子线程,在子线程处理UI相关操作会出现一些莫名的问题。

    小提示

    (1)创建一个操作,放在NSOperation队列中执行,默认是异步执行的。

    (2)mainqueue   返回一个和主线程相关的队列,即主队列。

    B.使用代理方法发送异步请求

    要监听服务器返回的data,所以使用<NSURLConnectionDataDelegate>协议

    常见大代理方法如下:

    #pragma mark- NSURLConnectionDataDelegate代理方法(异步请求)

     

    //当接收到服务器的响应(连通了服务器)时会调用

     

    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

        NSLog(@"接收到服务器的响应");

        //初始化数据

        self.responseData=[NSMutableData data];

    }

    //当接收到服务器的数据时会调用(可能会被调用多次,每次只传递部分数据)

    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

        NSLog(@"接收到服务器的数据");

        //拼接数据

        [self.responseData appendData:data];

    }

    //当服务器的数据加载完毕时就会调用

    -(void)connectionDidFinishLoading:(NSURLConnection *)connection{

        

    //    NSString *results = [[NSString alloc]

    //                         initWithBytes:[responseData bytes]

    //                         length:[responseData length]

    //                         encoding:NSUTF8StringEncoding];

    //    

    //    NSLog(@"connectionDidFinishLoading: %@",results);

     

        //数据返回的是json数组 这里直接把json数组转成OC数组

        NSArray *arr = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:nil];

     

        NSDictionary *dic = [arr objectAtIndex:0];

        NSArray *arrNew = [dic objectForKey:@"pollutants"];

        NSDictionary *dicNew = [arrNew objectAtIndex:0];

        msgLable.text = [NSString stringWithFormat:@"污染源:%@,污染指数:%@",[dicNew objectForKey:@"pol"],[dicNew objectForKey:@"value"]];

        

       

    }

    //请求错误(失败)的时候调用(请求超时断网没有网,一般指客户端错误)

    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

    {

         NSLog(@"Connection failed: %@", error);

    }

     

     

    //异步请求加载数据

    -(void)loadDataAsy{

        msgLable.text = @"数据加载中....";

        //请求的地址

        NSURL *url = [[NSURL alloc] initWithString:@"http://aqicn.org/publishingdata/json"];

        //创建请求

        //NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];

        //设置请求超时

        NSMutableURLRequest *req=[NSMutableURLRequest  requestWithURL:url];

        req.timeoutInterval=5.0;

        //创建连接

        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];

        [connection start];

    }

    补充:

    (1)数据的处理

    在didReceiveData:方法中,拼接接收到的所有数据,等所有数据都拿到后,在connectionDidFinishLoading:方法中进行处理

    (2)网络延迟

    在做网络开发的时候,一定要考虑到网络延迟情况的处理。

    最终的显示效果:

    如果对你有帮助,请关注我哦!

  • 相关阅读:
    Hadoop-CDH源码编译
    HBase框架基础(四)
    HBase框架基础(三)
    Scala基础简述
    HBase框架基础(一)
    NOI2015 软件包管理器
    可持久化数据结构入门
    树链剖分 入门
    NOIP2009 最优贸易
    高斯消元 模板
  • 原文地址:https://www.cnblogs.com/laolitou-ping/p/6255387.html
Copyright © 2011-2022 走看看