iOS网络请求GET&POST,同步&异步

    //网络编程
        //在iOS下面,网络编程主要分为3步
        //1.客户端发送请求
        //2.建立连接,获取数据
        //3.使用数据(根据用户的请求,使用所获取的数据)
//#warning 1.客户端发送请求(GET请求)
//    NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"];
//#warning 2.建立链接,获取数据
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//#warning 3.使用数据
//    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
//    NSLog(@"%@",dict);



//    NSURL *imageUrl = [NSURL URLWithString:@"http://img4.duitang.com/uploads/item/201204/05/20120405130619_YuzFh.jpeg"];
//    NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
//    UIImage *image = [UIImage imageWithData:imageData];
//    self.window.layer.contents = (id)image.CGImage;

    //展示图片
//    NSURL *url1 = [NSURL URLWithString:@"http://media.breadtrip.com/images/icons/country.png"];
//    NSURLRequest *request1 = [NSURLRequest requestWithURL:url1];
//    NSData *data1 = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];
//    UIImage *image = [UIImage imageWithData:data1];
//    UIImageView *imageView =[[UIImageView alloc] initWithImage:image];
//    [self.window addSubview:imageView];


//#warning 1.客户端发送请求(POST请求)
//    NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
//    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url];
//    [mutableRequest setHTTPMethod:@"POST"];
//    NSData *requestData = [@"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" dataUsingEncoding:NSUTF8StringEncoding];
//    [mutableRequest setHTTPBody:requestData];
//#warning 2.建立链接,获取数据
//    NSData *data = [NSURLConnection sendSynchronousRequest:mutableRequest returningResponse:nil error:nil];
//#warning 3.使用数据
//    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
//    NSLog(@"%@",dict);





    /**
     *  GET和POST的区别和联系
     联系:不管是GET还是POST,都是网络请求方式
     区别:
        GET:1.GET请求参数会直接跟在URL后面。容易暴露用户的相关信息。
             2.不管是NSURLRequest还是NSMutableURLRequest默认的请求方式都是GET
        POST:1.POST请求的参数不会跟在URL后面。而是使用setHTTPBody进行拼接
              2.使用POST的时候,由于需要进行参数拼接,所以需要使用NSMutableURLRequest。而且需要使用setHTTPMethod设置为POST
     */

//    GET请求
    NSURL *url = [NSURL URLWithString:@"http://api.breadtrip.com/destination/v3/"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLResponse *response = nil;
    NSError *error = nil;
    //sendSynchronousRequest这个方法有三个参数,一个返回值。
        //参数:
            //1.request:NSURLRequest或者NSMutableURLRequest
            //2.response:这个参数需要给response对应的地址。通过地址,可以修改这个response的值。这样用户就可以在外界使用。
            //3.error:这个参数需要给error对应的地址。通过地址修改error对应的值,用户也可以在外界使用
        //通过这个方法,需要学到一个知识点就是如果想要一个函数返回多个返回值的话,可以使用**.
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@",dict);
    NSLog(@"%@",response);

//    POST请求
//    NSURL *url = [NSURL URLWithString:@"http://www.xcar.com.cn/bbs/iphone5/bbsGetPostsByForumId.php"];
//    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url];
//    [mutableRequest setHTTPMethod:@"POST"];
//    NSData *requestData = [@"forumId=&type=0&offset=0&limit=20&uid=&ver=5.3.3" dataUsingEncoding:NSUTF8StringEncoding];
//    [mutableRequest setHTTPBody:requestData];
//    NSData *data = [NSURLConnection sendSynchronousRequest:mutableRequest returningResponse:nil error:nil];
//    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
//    NSLog(@"%@",dict);
#pragma mark - 同步
- (void)syn:(UIButton *)button
{
     //网络编程
        //1.请求
    NSURL *url = [NSURL URLWithString:kURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
        //2.连接
    //连接有两种方式:
    //1.同步连接 [NSURLConnection sendSynchronousRequest:]同步连接会卡死当前线程,只有当前数据请求结束之后,才会允许做其他操作。
    //2.异步连接 
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSLog(@"同步data%@",data);
        //3.使用数据
    NSLog(@"同步");
    NSError *error1 = nil;
    _player = [[AVAudioPlayer alloc] initWithData:data error:&error1];
    if (error == nil) {
        [_player prepareToPlay];
        [_player play];
    }

}

#pragma mark - 异步
- (void)asyn:(UIButton *)button
{
    //网络编程
        //1.请求
    NSURL *url = [NSURL URLWithString:kURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
        //2.连接(异步连接)
        //异步连接不会卡死主线程。在请求数据的过程中,允许用户做其他的操作。
        //1>使用[NSURLConnection sendAsynchronousRequest:]这个方法没有返回值。但是将data,response,error封装到了block中,可以允许程序员直接使用。
    NSOperationQueue *queue = [NSOperationQueue currentQueue];

    NSLog(@"queue:%@",queue);
    NSLog(@"mainQueue:%@",[NSOperationQueue mainQueue]);
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"response:%@",response);
        NSLog(@"data:%@",data);
        NSLog(@"error:%@",connectionError);

        NSError *error = nil;
        _player = [[AVAudioPlayer alloc] initWithData:data error:&error];
        if (error == nil) {
            [_player prepareToPlay];
            [_player play];
        }
    }];

    NSLog(@"异步");
}
#pragma mark - 异步2
- (void)asyn3:(UIButton *)button
{    //网络编程
    //1.请求
    NSURL *url = [NSURL URLWithString:kURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    //2.连接
//    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [NSURLConnection connectionWithRequest:request delegate:self];

    NSLog(@"再异步");
}
#pragma mark - NSURLConnectionDataDelegation
//接收到服务器回应执行
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    _total = response.expectedContentLength;
    NSLog(@"responseLenth:%lld",response.expectedContentLength);
}
//接收到数据之后一直执行
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_mutableData appendData:data];
    _progressView.progress = 1.0 * _mutableData.length / _total;
}
//出错的时候执行
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"出错的时候执行");
}
//请求完毕执行
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSError *error = nil;
    _player = [[AVAudioPlayer alloc] initWithData:_mutableData error:&error];
    if (error == nil) {
        [_player prepareToPlay];
        [_player play];
    }
    NSLog(@"下载完成之后执行");
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值