iOS学习笔记(八)——iOS网络通信http之NSURLConnection

移动互联网时代,网络通信已是手机终端必不可少的功能。我们的应用中也必不可少的使用了网络通信,增强客户端与服务器交互。这一篇提供了使用NSURLConnection实现http通信的方式。

          NSURLConnection提供了异步请求、同步请求两种通信方式。

1、异步请求

       iOS5.0 SDK NSURLConnection类新增的sendAsynchronousRequest:queue:completionHandler:方法,从而使iOS5支持两种异步请求方式。我们先从新增类开始。

 

1)sendAsynchronousRequest

iOS5.0开始支持sendAsynchronousReques方法,方法使用如下:

 

  1. - (void)httpAsynchronousRequest{ 
  2.  
  3.     NSURL *url = [NSURL URLWithString:@"http://url"]; 
  4.      
  5.     NSString *post=@"postData"
  6.      
  7.     NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
  8.  
  9.     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
  10.     [request setHTTPMethod:@"POST"]; 
  11.     [request setHTTPBody:postData]; 
  12.     [request setTimeoutInterval:10.0]; 
  13.      
  14.     NSOperationQueue *queue = [[NSOperationQueue alloc]init]; 
  15.     [NSURLConnection sendAsynchronousRequest:request 
  16.                                        queue:queue 
  17.                            completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){ 
  18.                                if (error) { 
  19.                                    NSLog(@"Httperror:%@%d", error.localizedDescription,error.code); 
  20.                                }else
  21.                                     
  22.                                    NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode]; 
  23.                                     
  24.                                    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
  25.                                     
  26.                                    NSLog(@"HttpResponseCode:%d", responseCode); 
  27.                                    NSLog(@"HttpResponseBody %@",responseString); 
  28.                                } 
  29.                            }]; 
  30.  
  31.      
 

      sendAsynchronousReques可以很容易地使用NSURLRequest接收回调,完成http通信。

2)connectionWithRequest

iOS2.0就开始支持connectionWithRequest方法,使用如下:

 

  1. - (void)httpConnectionWithRequest{ 
  2.      
  3.     NSString *URLPath = [NSString stringWithFormat:@"http://url"]; 
  4.     NSURL *URL = [NSURL URLWithString:URLPath]; 
  5.     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; 
  6.     [NSURLConnection connectionWithRequest:request delegate:self]; 
  7.      
  8.  
  9. - (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response 
  10.     
  11.     NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode]; 
  12.     NSLog(@"response length=%lld  statecode%d", [response expectedContentLength],responseCode); 
  13.  
  14.  
  15. // A delegate method called by the NSURLConnection as data arrives.  The 
  16. // response data for a POST is only for useful for debugging purposes, 
  17. // so we just drop it on the floor. 
  18. - (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data 
  19.     if (mData == nil) { 
  20.         mData = [[NSMutableData alloc] initWithData:data]; 
  21.     } else
  22.         [mData appendData:data]; 
  23.     } 
  24.     NSLog(@"response connection"); 
  25.  
  26. // A delegate method called by the NSURLConnection if the connection fails. 
  27. // We shut down the connection and display the failure.  Production quality code 
  28. // would either display or log the actual error. 
  29. - (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error 
  30.      
  31.     NSLog(@"response error%@", [error localizedFailureReason]); 
  32.  
  33. // A delegate method called by the NSURLConnection when the connection has been 
  34. // done successfully.  We shut down the connection with a nil status, which 
  35. // causes the image to be displayed. 
  36. - (void)connectionDidFinishLoading:(NSURLConnection *)theConnection 
  37.     NSString *responseString = [[NSString alloc] initWithData:mData encoding:NSUTF8StringEncoding]; 
  38.      NSLog(@"response body%@", responseString); 

 

  connectionWithRequest需要delegate参数,通过一个delegate来做数据的下载以及Request的接受以及连接状态,此处delegate:self,所以需要本类实现一些方法,并且定义mData做数据的接受。

需要实现的方法:

 

1、获取返回状态、包头信息。

 

  1. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; 
 

2、连接失败,包含失败。

  1. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; 

3、接收数据

  1. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; 

 

4、数据接收完毕

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

 

 

    connectionWithRequest使用起来比较繁琐,而iOS5.0之前用不支持sendAsynchronousRequest。有网友提出了AEURLConnection解决方案。

 

  1. AEURLConnection is a simple reimplementation of the API for use on iOS 4. Used properly, it is also guaranteed to be safe against The Deallocation Problem, a thorny threading issue that affects most other networking libraries. 

 

2、同步请求

同步请求数据方法如下:

 

  1. - (void)httpSynchronousRequest{ 
  2.      
  3.     NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]]; 
  4.     NSURLResponse * response = nil; 
  5.     NSError * error = nil; 
  6.     NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest 
  7.                                           returningResponse:&response 
  8.                                                       error:&error]; 
  9.      
  10.     if (error == nil) 
  11.     { 
  12.         // 处理数据 
  13.     } 
 

同步请求数据会造成主线程阻塞,通常在请求大数据或网络不畅时不建议使用。

 

        从上面的代码可以看出,不管同步请求还是异步请求,建立通信的步骤基本是一样的:

         1、创建NSURL

         2、创建Request对象

         3、创建NSURLConnection连接。

         NSURLConnection创建成功后,就创建了一个http连接。异步请求和同步请求的区别是:创建了异步请求,用户可以做其他的操作,请求会在另一个线程执行,通信结果及过程会在回调函数中执行。同步请求则不同,需要请求结束用户才能做其他的操作。

posted @ 2013-09-03 12:58  李小见  阅读(212)  评论(0编辑  收藏  举报