NSURLConnection的使用

通过NSURLConnection进行异步下载   

      NSURLConnection 提供了两种方式来实现连接,一种是同步的另一种是异步的,异步的连接将会创建一个新的线程,这个线程将会来负责下载的动作。而对于同步连接,在下载连接和处理通讯时,则会阻塞当前调用线程。

     许多开发者都会认为同步的连接将会堵塞主线程,其实这种观点是错误的。一个同步的连接是会阻塞调用它的线程。如果你在主线程中创建一个同步连接,没错,主线程会阻塞。但是如果你并不是从主线程开启的一个同步的连接,它将会类似异步的连接一样。因此这种情况并不会堵塞你的主线程。事实上,同步和异步的主要区别就是运行 runtime 为会异步连接创建一个线程,而同步连接则不会。

[objc]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //asynchronousRequest connection  
  2. -(void)fetchAppleHtml{  
  3.     NSString *urlString = @"http://www.apple.com";  
  4.     NSURL *url = [NSURL URLWithString:urlString];  
  5. //    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];  
  6.     NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0f]; //maximal timeout is 30s  
  7.       
  8.     NSOperationQueue *queue = [[NSOperationQueue alloc] init];  
  9.     [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {  
  10.         if ([data length] > 0 && connectionError == nil) {  
  11.             NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];  
  12.             NSString *filePath = [documentsDir stringByAppendingPathComponent:@"apple.html"];  
  13.             [data writeToFile:filePath atomically:YES];  
  14.             NSLog(@"Successfully saved the file to %@",filePath);  
  15.             NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  
  16.             NSLog(@"HTML = %@",html);  
  17.         }else if ([data length] == 0 && connectionError == nil){  
  18.             NSLog(@"Nothing was downloaded.");  
  19.         }else if (connectionError != nil){  
  20.             NSLog(@"Error happened = %@",connectionError);  
  21.         }  
  22.     }];  
  23. }  

      通过NSURLConnection进行同步下载   

   使用 NSURLConnection 的 sendSynchronousRequest:returningResponse:error:类方法,我们可以进行同步请求。在创建一个同步的网络连接的时候我们需要明白一点,并不是是我们的这个同步连接一定会堵塞我们的主线程,如果这个同步的连接是创建在主线程上的,那么这种情况下是会堵塞我们的主线程的,其他的情况下是不一定会堵塞我们的主线程的。如果你在 GCD 的全局并发队列上初始化了一个同步的连接,你其实并不会堵塞我们的主线程的。

   我们来初始化第一个同步连接,并看看会发生什么。在实例中,我们将尝试获取 Yahoo!美国站点主页内容: 


[objc]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //synchronousRequest connection  
  2. -(void)fetchYahooData{  
  3.     NSLog(@"We are here...");  
  4.     NSString *urlString = @"http://www.yahoo.com";  
  5.     NSURL *url = [NSURL URLWithString:urlString];  
  6.     NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];  
  7.     NSURLResponse *response = nil;  
  8.     NSError *error = nil;  
  9.     NSLog(@"Firing synchronous url connection...");  
  10.     NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];  
  11.     if ([data length] > 0 && error == nil) {  
  12.         NSLog(@"%lu bytes of data was returned.",(unsigned long)[data length]);  
  13.     }else if([data length] == 0 && error == nil){  
  14.         NSLog(@"No data was return.");  
  15.     }else if (error != nil){  
  16.         NSLog(@"Error happened = %@",error);  
  17.     }  
  18.     NSLog(@"We are done.");  
  19.       
  20. }  
  21. /* 
  22.  | 
  23.  | as we know, it will chock main thread when we call sendSynchronousRequest on main thread,,,,change below 
  24.  | 
  25.  v 
  26. */  
  27. //call sendSynchronousRequest on GCD pool  
  28. -(void)fetchYahooData2_GCD{  
  29.     NSLog(@"We are here...");  
  30.     NSString *urlString = @"http://www.yahoo.com";  
  31.     NSLog(@"Firing synchronous url connection...");  
  32.     dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);  
  33.     dispatch_async(dispatchQueue, ^{  
  34.         NSURL *url = [NSURL URLWithString:urlString];  
  35.         NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];  
  36.         NSURLResponse *response = nil;  
  37.         NSError *error = nil;  
  38.         NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];  
  39.         if ([data length] > 0 && error == nil) {  
  40.             NSLog(@"%lu bytes of data was returned.",(unsigned long)[data length]);  
  41.         }else if ([data length] == 0 && error == nil){  
  42.             NSLog(@"No data was returned.");  
  43.         }else if (error != nil){  
  44.             NSLog(@"Error happened = %@",error);  
  45.         }  
  46.     });  
  47.     NSLog(@"We are done.");  
  48.   
  49. }  

查看运行输出结果,分别为:

synchronous download on main thread without GCD


synchronous download on main thread with GCD


    可以看到在主线程上调用同步下载会阻塞当前线程,而使用GCD则不会。

    通过NSURLConnection发送一个HTTP GET请求

[objc]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //send a GET request to server with some params  
  2. -(void)httpGetWithParams{  
  3.     NSString *urlString = @"http://chaoyuan.sinaapp.com";  
  4.     urlString = [urlString stringByAppendingString:@"?p=1059"];  
  5.     NSURL *url = [NSURL URLWithString:urlString];  
  6.     NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];  
  7.     [urlRequest setTimeoutInterval:30.0f];  
  8.     [urlRequest setHTTPMethod:@"GET"];  
  9.     NSOperationQueue *queue = [[NSOperationQueue alloc] init];  
  10.     [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {  
  11.         if ([data length] > 0 && connectionError == nil) {  
  12.             NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  
  13.             NSLog(@"HTML = %@",html);  
  14.         }else if([data length] == 0 && connectionError == nil){  
  15.             NSLog(@"nothing was download.");  
  16.         }else if(connectionError != nil){  
  17.             NSLog(@"Error happened = %@",connectionError);  
  18.         }  
  19.     }];  
  20. }  


  通过NSURLConnection发送一个HTTP POST请求

[objc]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //send a POST request to a server with some params  
  2. -(void)httpPostWithParams{  
  3.     NSString *urlAsString = @"http://chaoyuan.sinaapp.com";  
  4.     urlAsString = [urlAsString stringByAppendingString:@"?param1=First"];  
  5.     urlAsString = [urlAsString stringByAppendingString:@"¶m2=Second"];  
  6.     NSURL *url = [NSURL URLWithString:urlAsString];  
  7.     NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setTimeoutInterval:30.0f];  
  8.     [urlRequest setHTTPMethod:@"POST"];  
  9.     NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2"; [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]]; NSOperationQueue *queue = [[NSOperationQueue alloc] init];  
  10.     [NSURLConnection  
  11.      sendAsynchronousRequest:urlRequest  
  12.      queue:queue completionHandler:^(NSURLResponse *response, NSData *data,  
  13.                                      NSError *error) {  
  14.          if ([data length] >0 &&  
  15.              error == nil){  
  16.              NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"HTML = %@", html);  
  17.          }  
  18.          else if ([data length] == 0 &&  
  19.                   error == nil){  
  20.              NSLog(@"Nothing was downloaded.");  
  21.          }  
  22.          else if (error != nil){  
  23.              NSLog(@"Error happened = %@", error);  
  24.          }  
  25.      }];  
  26. }  

tips:

    except http get and post there are http delete and put and something else, if you are crazy about http, please GOOGLE!

完整项目代码在这里

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值