iOS網絡通信http之NSURLConnection

文章來源:http://blog.csdn.net/xyz_lmn/article/details/8968182


 移動互聯網時代,網絡通信已是手機終端必不可少的功能。我們的應用中也必不可少的使用了網絡通信,增強客戶端與服務器交互。這一篇提供了使用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.       
  32. }  

      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.   
  10. - (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response  
  11. {  
  12.      
  13.     NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];  
  14.     NSLog(@"response length=%lld  statecode%d", [response expectedContentLength],responseCode);  
  15. }  
  16.   
  17.   
  18. // A delegate method called by the NSURLConnection as data arrives.  The  
  19. // response data for a POST is only for useful for debugging purposes,  
  20. // so we just drop it on the floor.  
  21. - (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data  
  22. {  
  23.     if (mData == nil) {  
  24.         mData = [[NSMutableData alloc] initWithData:data];  
  25.     } else {  
  26.         [mData appendData:data];  
  27.     }  
  28.     NSLog(@"response connection");  
  29. }  
  30.   
  31. // A delegate method called by the NSURLConnection if the connection fails.  
  32. // We shut down the connection and display the failure.  Production quality code  
  33. // would either display or log the actual error.  
  34. - (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error  
  35. {  
  36.       
  37.     NSLog(@"response error%@", [error localizedFailureReason]);  
  38. }  
  39.   
  40. // A delegate method called by the NSURLConnection when the connection has been  
  41. // done successfully.  We shut down the connection with a nil status, which  
  42. // causes the image to be displayed.  
  43. - (void)connectionDidFinishLoading:(NSURLConnection *)theConnection  
  44. {  
  45.     NSString *responseString = [[NSString alloc] initWithData:mData encoding:NSUTF8StringEncoding];  
  46.      NSLog(@"response body%@", responseString);  
  47. }  


   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.     }  
  14. }  


同步請求數據會造成主線程阻塞,通常在請求大數據或網絡不暢時不建議使用。


        從上面的代碼可以看出,不管同步請求還是異步請求,建立通信的步驟基本是一樣的:

         1、創建NSURL

         2、創建Request對象

         3、創建NSURLConnection連接。

         NSURLConnection創建成功後,就創建了一個http連接。異步請求和同步請求的區別是:創建了異步請求,用戶可以做其他的操作,請求會在另一個線程執行,通信結果及過程會在回調函數中執行。同步請求則不同,需要請求結束用戶才能做其他的操作。


/**
* @author 張興業
*  iOS入門羣:83702688
*  android開發進階羣:241395671
*  我的新浪微博:@張興業TBOW
*/

參考:
http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE
http://codewithchris.com/tutorial-how-to-use-ios-nsurlconnection-by-example/
http://kelp.phate.org/2011/06/ios-stringwithcontentsofurlnsurlconnect.html


發佈了64 篇原創文章 · 獲贊 5 · 訪問量 32萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章