移動網際網路時代,網絡通信已是手機終端必不可少的功能。我們的應用中也必不可少的使用了網絡通信,增強用戶端與伺服器互動。這一篇提供了使用NSURLConnection實作http通信的方式。
NSURLConnection提供了異步請求、同步請求兩種通信方式。
1、異步請求
iOS5.0 SDK NSURLConnection類新增的sendAsynchronousRequest:queue:completionHandler:方法,進而使iOS5支援兩種異步請求方式。我們先從新增類開始。
1)sendAsynchronousRequest
iOS5.0開始支援sendAsynchronousReques方法,方法使用如下:
- (void)httpAsynchronousRequest{ NSURL *url = [NSURL URLWithString:@"http://url"]; NSString *post=@"postData"; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:postData]; [request setTimeoutInterval:10.0]; NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){ if (error) { NSLog(@"Httperror:%@%d", error.localizedDescription,error.code); }else{ NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode]; NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"HttpResponseCode:%d", responseCode); NSLog(@"HttpResponseBody %@",responseString); } }]; }
sendAsynchronousReques可以很容易地使用NSURLRequest接收回調,完成http通信。
2)connectionWithRequest
iOS2.0就開始支援connectionWithRequest方法,使用如下:
- (void)httpConnectionWithRequest{ NSString *URLPath = [NSString stringWithFormat:@"http://url"]; NSURL *URL = [NSURL URLWithString:URLPath]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; [NSURLConnection connectionWithRequest:request delegate:self]; } - (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response { NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode]; NSLog(@"response length=%lld statecode%d", [response expectedContentLength],responseCode); } // A delegate method called by the NSURLConnection as data arrives. The // response data for a POST is only for useful for debugging purposes, // so we just drop it on the floor. - (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data { if (mData == nil) { mData = [[NSMutableData alloc] initWithData:data]; } else { [mData appendData:data]; } NSLog(@"response connection"); } // A delegate method called by the NSURLConnection if the connection fails. // We shut down the connection and display the failure. Production quality code // would either display or log the actual error. - (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error { NSLog(@"response error%@", [error localizedFailureReason]); } // A delegate method called by the NSURLConnection when the connection has been // done successfully. We shut down the connection with a nil status, which // causes the image to be displayed. - (void)connectionDidFinishLoading:(NSURLConnection *)theConnection { NSString *responseString = [[NSString alloc] initWithData:mData encoding:NSUTF8StringEncoding]; NSLog(@"response body%@", responseString); }
connectionWithRequest需要delegate參數,通過一個delegate來做資料的下載下傳以及Request的接受以及連接配接狀态,此處delegate:self,是以需要本類實作一些方法,并且定義mData做資料的接受。
需要實作的方法:
1、擷取傳回狀态、標頭資訊。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
2、連接配接失敗,包含失敗。
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
3、接收資料
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
4、資料接收完畢
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
connectionWithRequest使用起來比較繁瑣,而iOS5.0之前用不支援sendAsynchronousRequest。有網友提出了AEURLConnection解決方案。
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、同步請求
同步請求資料方法如下:
- (void)httpSynchronousRequest{ NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]]; NSURLResponse * response = nil; NSError * error = nil; NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error]; if (error == nil) { // 處理資料 } }
同步請求資料會造成主線程阻塞,通常在請求大資料或網絡不暢時不建議使用。
從上面的代碼可以看出,不管同步請求還是異步請求,建立通信的步驟基本是一樣的:
1、建立NSURL
2、建立Request對象
3、建立NSURLConnection連接配接。
/**
* @author 張興業
* http://blog.csdn.net/xyz_lmn
* 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