6.15 网络请求,Get和Post,同步和异步

sendSynchronizedGetRequest; //同步get
sendAsynchronizedGetRequest; //异步get
sendSynchronizedPostRequest; //同步post
sendAsynchronizedPostRequest; //异步post

Get和Post总结:客户端从服务器请求数据,主要区别是安全性,
③Get请求,将参数直接写在访问路径上,容易被外界看到,安全性不高,地址最多255字节;
④Post请求,将参数放到body里面,安全性高,不易被捕获;

同步和异步:是服务器端到客户端的数据返回,主要区别是加载的速度
①同步请求一旦发送,程序将停止用户交互,直至服务器返回数据完成,Get和Post同步请求的时候最常见的是登录,输入各种密码才能看到的功能,必须是同步,异步在局部刷新的时候用的比较多,比较耗时的时候执行异步请求,可以让客户先看到一部分功能,然后慢慢刷新。

②异步请求不会阻塞主线程,会建立一个新的线程来操作,发出异步请求后,依然可以对UI进行操作,程序可以继续运行;异步实现的时候需要实现协议NSURLConnectionDataDelegate,

sendSynchronizedGetRequest; //同步get

get方法的请求参数是放在长长的URL字符串里面,是一串明文。
用字符串构建NSURL,最好在使用URLWithString的时候把原字符串进行一下UTF8转码,关于为何要转码,看下这里第一部分。然后NSURL对象构建NSURLRequest,使用NSURLConnection的同步方法,传入request对象就可以通过get方法获取数据。

这里有个NSError对象地址传入,用于做错误判断,网络的实际情况是多变的,必须要考虑请求错误的情况,否则可能导致程序奔溃。


#pragma mark - 网络请求
 //同步get
- (void)sendSynchronizedGetRequest
{
    //1,创建URL对象
    NSURL *url = [NSURL URLWithString:GET_URL];
    //2,创建URLRequest
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
    //3,发送请求
    //3.1 创建error对象
    NSError *error = nil;

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

    //3.2 断言(帮助快速定位到崩溃的位置,optional)
    NSString *errorString = [error localizedDescription];

    //当前者条件为假的时候,进行崩溃,崩溃原因为后面参数所写
    NSAssert(!error,errorString);
    //解析数据
    id obj = [self jsonWithData:data];

    NSLog(@"%@",obj);

    //判定
    if ([obj[@"error_code"] integerValue] == 0) {
        //5.1更改数据源
        self.dataSource = [obj[@"result"][@"data"] mutableCopy];
        //5.2更新表格视图
        [self.tableView reloadData];
    }
    //停止动画
    [self.indicatorView stopAnimating];


}

sendAsynchronizedGetRequest; //异步get

//异步get
- (void)sendAsynchronizedGetRequest
{
    //1,创建URL对象
    NSURL *url = [NSURL URLWithString:GET_URL];
    //2,创建URLRequest
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
    //3,发送请求,以代理的方式
    [NSURLConnection connectionWithRequest:request delegate:self];


}

#pragma mark - NSURLConnectionDataDelegate
//请求失败的时候调用
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"请求失败");
}
//接受到数据的时候调用(调用次数>=0)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //添加数据流
    [self.data appendData:data];

}
//请求完成时候调用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //4,解析数据
    id obj = [self jsonWithData:self.data];
    //判定
    if ([obj[@"error_code"] integerValue] == 0) {
        //5.1更改数据源
        self.dataSource = [obj[@"result"][@"data"] mutableCopy];
        //5.2更新表格视图
        [self.tableView reloadData];
    }
    //6,清空数据流,否则下次请求异常
    self.data.length = 0 ;

    //7,停止转动
    [self.indicatorView stopAnimating];
}

sendSynchronizedPostRequest; //同步post

//同步post
- (void)sendSynchronizedPostRequest
{
    //1,创建URL对象
    NSURL *url = [NSURL URLWithString:POST_URL];
    //2,创建URLRequest
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    //2.1 配置request
    //设置请求时长
    urlRequest.timeoutInterval = 10;
    //设置请求方式
    urlRequest.HTTPMethod = @"POST";
    //设置请求body
    NSDictionary *dic = @{@"key":APP_KEY,@"menu":[self urlEncodeString:@"回锅肉"]};
    urlRequest.HTTPBody = [self dataWithDic:dic];

    //3,发送请求
    //3.1 创建error对象
    NSError *error = nil;

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

    //3.2 断言(帮助快速定位到崩溃的位置,optional)
    NSString *errorString = [error localizedDescription];
    //解析数据
    id obj = [self `jsonWithData:data`];
    //判定
    if ([obj[@"error_code"] integerValue] == 0) {
        //5.1更改数据源
        self.dataSource = [obj[@"result"][@"data"] mutableCopy];
        //5.2更新表格视图
        [self.tableView reloadData];
    }
    //停止动画
    [self.indicatorView stopAnimating];

}

sendAsynchronizedPostRequest; //异步post


//异步post
- (void)sendAsynchronizedPostRequest
异步post类似,不再是使用NSURLConnection调用方法直接得到数据,而是使用构建一个NSURLConnection对象,这个方法会默认开始请求数据。接下来关键就是靠委托了。因为请求的时间未知,所以使用委托模式的回调作用,在数据回来是调用协议方法。post和get委托方法处理一样。


协议方法:

要注意的是这里有两个委托:NSURLConnectionDataDelegate和NSURLConnectionDelegate,前一个继承于后一个,获取数据的方法是定义在前一个委托里面的,所以只要遵循NSURLConnectionDataDelegate就可以了。

{
    //1,创建URL对象
    NSURL *url = [NSURL URLWithString:POST_URL];
    //2,创建URLRequest
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    //2.1 配置request
    //设置请求时长
    urlRequest.timeoutInterval = 10;
    //设置请求方式
    urlRequest.HTTPMethod = @"POST";
    //设置请求body
    NSDictionary *dic = @{@"key":APP_KEY,@"menu":[self urlEncodeString:@"回锅肉"]};
    urlRequest.HTTPBody = [self dataWithDic:dic];
    //3,发送请求,以代理的方式
    [NSURLConnection connectionWithRequest:urlRequest delegate:self];

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值