打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
NSURLConnection的使用

      通过NSURLConnection进行异步下载   

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

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

  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进行同步下载   

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

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


  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请求

  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请求

  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!

完整项目代码在这里


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
IOS学习笔记(16)网络请求,json解析
iOS开发中的网络请求
IOS开发使用NSURLConnection、NSURLSession、AFN、ASI四种方式实现HTTP请求
ios网络请求 get
iOS网络通信http之NSURLConnection
iOS网络请求 get、post区别
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服