zoukankan      html  css  js  c++  java
  • 同步 和 异步网络请求

    //同步请求可以一次性的接收所有数据  但是在主线程中完成  会阻塞主线程

    -(void)sendRequestTongbu

    {

        //创建一个NSSring类型的URL连接字符串

        NSString *urlString = @"http://www.apple.com";

        //转换成NSURL类型

        NSURL *url = [NSURL URLWithString:urlString];

        //实例化一个request,把URL对象赋值到NSURLRequest对象中

        NSURLRequest *request = [NSURLRequest requestWithURL:url];

        NSError *error = nil;

        //获得数据

        NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:&error];

        

        //在下载完数据后,一般都需要做data是否为空的判断

        if (data == nil)

        {

            NSLog(@"send request failed");

            return;

            

        }

        NSString *str = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];

        NSLog(@"%@",str);

    }

    //异步请求  需要在代理中接收数据  不会阻塞当前线程 记得加上<NSURLConnectionDataDelegate>

    -(void)senderRequestYibu

    {

        NSString *urlString = @"http://www.cnblogs.com/chenhaosuibi/";

        NSURL *url = [NSURL URLWithString:urlString];

        NSURLRequest *resquest = [NSURLRequest requestWithURL:url];

        

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

        

        if (connection) {

            NSLog(@"链接成功");

        }

        else

            

        {

            NSLog(@"链接失败");

        }

    }

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

    {

        NSLog(@"收到响应,请求成功");

        NSLog(@"%@",response);

        // 可以在里面判断返回结果, 或者处理返回的http头中的信息

    }

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

    {

        NSLog(@"收到了Data");

        NSString *dataStr = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];

        NSLog(@"dataStr = %@",dataStr);

    }

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection

    {

        NSLog(@"全部接受完数据后触发");

    }

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

    {

        NSLog(@"链接出错");

        NSLog(@"%@",error);

    }

  • 相关阅读:
    Java操作redis
    Ajax & Json
    【转载】K8s-Pod时区与宿主时区时区同步
    【转载】Python中如何将字符串作为变量名
    【转载】python实现dubbo接口的调用
    机器学习避坑指南:训练集/测试集分布一致性检查
    机器学习深度研究:特征选择中几个重要的统计学概念
    机器学习数学基础:学习线性代数,千万不要误入歧途!推荐一个正确学习路线
    被 Pandas read_csv 坑了
    print('Hello World!')的新玩法
  • 原文地址:https://www.cnblogs.com/chenhaosuibi/p/3442379.html
Copyright © 2011-2022 走看看