一、介紹
NSURLConnection通過提供的 URL request加載url的內容。NSURLConnection僅僅提供開始和取消網絡請求,需要你在url 請求對象中自己進行配置。系統提供三個協議,NSURLConnectionDelegate 和 NSURLConnectionDataDelegate便於我們進行更好的控制。
NSURLConnection類與三個正式協議協同工作:NSURLConnectionDelegate,NSURLConnectionDataDelegate,以及NSURLConnectionDownloadDelegate.爲了使用這些協議,其中NSURLConnectionDelegate 協議主要是用來進行證書處理,也處理連接完成。因爲在數據傳輸過程中還處理連接失敗,所以所有關於連接的請求都需要實現這個協議。通常不是Newsstand
kit 操作,都需要實現NSURLConnectionDataDelegate協議,
二、屬性和方法
1、預處理連接請求
+ (BOOL)canHandleRequest:(NSURLRequest * nonnull)request 判斷連接請求是否可行。
2、URL請求信息
@property(readonly,copy)NSURLRequest *originalRequest
@property(readonly,copy)NSURLRequest *currentRequest 獲取當前的請求。
3、同步請求
+ (NSData * nullable)sendSynchronousRequest:(NSURLRequest * nonnull)request returningResponse:(NSURLResponse * nullable * nullable)response error:(NSError * nullable * nullable)error
4、異步請求
+ (NSURLConnection * nullable)connectionWithRequest:(NSURLRequest * nonnull)request delegate:(id nullable)delegate
- (instancetype nullable)initWithRequest:(NSURLRequest * nonnull)request delegate:(id nullable)delegate
- (instancetype nullable)initWithRequest:(NSURLRequest * nonnull)request delegate:(id nullable)delegate startImmediately:(BOOL)startImmediately
+ (void)sendAsynchronousRequest:(NSURLRequest * nonnull)request queue:(NSOperationQueue * nonnull)queue completionHandler:(void (^ nonnull)(NSURLResponse * nullable response, NSData * nullable data, NSError * nullable connectionError))handler
- (void)start 當startImmediately爲NO時
5、暫停連接
- (void)cancel
6、調度委託方法startImmediately爲NO時
- (void)scheduleInRunLoop:(NSRunLoop * nonnull)aRunLoop forMode:(NSString * nonnull)mode
- (void)setDelegateQueue:(NSOperationQueue * nullable)queue
- (void)unscheduleFromRunLoop:(NSRunLoop * nonnull)aRunLoop forMode:(NSString * nonnull)mode
三、實際例子
NSString *urlAddress= @"192.168.2.235/xampp/bl/login.xml";
NSString *encodeUrl = [urlAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodeUrl]];
request.HTTPMethod = @"POST";
request.timeoutInterval = 60 ;
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
BLMultipartForm *form = [[BLMultipartForm alloc] init];
[form addValue:@"zhangsan" forField:@"username"];
[form addValue:@"123456" forField:@"password"];
request.HTTPBody = [form httpBody];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError) {
NSLog(@"%@", connectionError);
}
else {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"HttpResponseBody %@",responseString);
}
}];
NSString *URLString = @"http://192.168.199.141/xampp/bl/login.xml";
// GET eg, http://xxxx.com/login.json?username=zhangsan&password=123456
URLString = [NSString stringWithFormat:@"%@?username=%@&password=%@", URLString, userName, password];
NSString *encodedURLString
= [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *URL = [NSURL URLWithString:encodedURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = @"GET";
request.timeoutInterval = 60;
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
self.URLConnection = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:YES];
NSString *URLString = @"http://192.168.199.141/xampp/bl/login.xml";
NSString *encodedURLString
= [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *URL = [NSURL URLWithString:encodedURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = @"POST";
request.timeoutInterval = 60;
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
BLMultipartForm *form = [[BLMultipartForm alloc] init];
[form addValue:userName forField:@"username"];
[form addValue:password forField:@"password"];
request.HTTPBody = [form httpBody];
self.URLConnection = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:YES];
#pragma mark - NSURLConnectionDataDelegate methods
- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) { // 連接成功
self.receivedData = [NSMutableData data];
}else {
// 請求錯誤,錯誤處理。
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *string = [[NSString alloc] initWithData:self.receivedData
encoding:NSUTF8StringEncoding];
NSLog(@"%@", string);
BLLoginRequestParser *parser = [[BLLoginRequestParser alloc] init];
// BLUser *user = [parser parseJson:self.receivedData];
BLUser *user = [parser parseXML:self.receivedData];
if ([_delegate respondsToSelector:@selector(requestSuccess:user:)]) {
[_delegate requestSuccess:self user:user];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%@", error);
if ([_delegate respondsToSelector:@selector(requestFailed:error:)]) {
[_delegate requestFailed:self error:error];
}
}
總結: 網絡請求的步驟如下:
1、創建NSURL對象,包含需要請求的URL地址
2、創建NSURLRequest請求對象,可以在request對象中添加額外數據:header和body相關參數
3、創建NSURLConnection連接。
請求中需要根據請求的方法去實現delegate,如果是sendAsynchronousRequest 方法,則可以在block中對結果進行處理。其它的請求則需要實現相關代理方法
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
基本就是按這個模式來,不過2013年後,iOS 7 和 Mac OS X 10.9 Mavericks對 Foundation URL 加載系統的徹底重構,蘋果推出NSURLSession來替代NSURLConnection。接下來會講解一些NSURLSession