一:NSURLConnection(IOS9.0已經棄用)是早期apple提供的http訪問方式。以下列出了常用的幾個場景:GET請求,POST請求,Response中帶有json數據 對於NSURLConnection有以下註意事項:(1)sendAsynchronourequest: queue
一:NSURLConnection(IOS9.0已經棄用)是早期apple提供的http訪問方式。以下列出了常用的幾個場景:GET請求,POST請求,Response中帶有json數據
對於NSURLConnection有以下註意事項:(1)sendAsynchronourequest: queue: completionHandler:函數中的queue參數表示的是“handler 這個block運行在queue中,如果queue為mainThread,那麼hanlder就運行在主線程;所以在處理UI的時候需要註意這個參數”
(1)Get請求(返迴文本)
//Request NSMutableURLRequest *urlRequest = [NSMutableURLRequest new]; [urlRequest setURL:[NSURL URLWithString:@"http://XXX.sinaapp.com/test/test.php?namr&id=43"]]; [urlRequest setTimeoutInterval:10.0f]; [urlRequest setHTTPMethod:@"GET"]; [urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData]; NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//根據回覆Headers,確認是是否為NSHTTPURLResponse的對象 if([response isKindOfClass:[NSHTTPURLResponse class]]){ NSHTTPURLResponse *resHttp = (NSHTTPURLResponse *)response; NSLog(@"status = %ld",resHttp.statusCode);//200 304 401...... NSDictionary *dicHeader = resHttp.allHeaderFields; NSLog(@"headers = %@",dicHeader); } else{ NSLog(@"not http"); }
if(data){ NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",html); } }];
(2)POST請求(返迴文本)
//Request NSMutableURLRequest *urlRequest = [NSMutableURLRequest new]; [urlRequest setURL:[NSURL URLWithString:@"http://XXX.sinaapp.com/test/test.php"]]; [urlRequest setTimeoutInterval:10.0f]; [urlRequest setHTTPMethod:@"POST"]; [urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData]; NSString *strBody = @"p1=abc&p2=12"; [urlRequest setHTTPBody:[strBody dataUsingEncoding:NSUTF8StringEncoding]]; NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { //確認是http if([response isKindOfClass:[NSHTTPURLResponse class]]){ NSHTTPURLResponse *resHttp = (NSHTTPURLResponse *)response; NSLog(@"status = %ld",resHttp.statusCode);//200 304 401...... NSDictionary *dicHeader = resHttp.allHeaderFields; NSLog(@"headers = %@",dicHeader); } else{ NSLog(@"not http"); } if(data){ NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",html); } }];
(3)Response中有Json數據
//Request NSMutableURLRequest *urlRequest = [NSMutableURLRequest new]; [urlRequest setURL:[NSURL URLWithString:@"http://XXX.sinaapp.com/test/test.php"]]; [urlRequest setTimeoutInterval:10.0f]; [urlRequest setHTTPMethod:@"POST"]; [urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData]; NSString *strBody = @"p1=abc&p2=12"; [urlRequest setHTTPBody:[strBody dataUsingEncoding:NSUTF8StringEncoding]]; NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { NSError *err2 = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err2]; if([jsonObject isKindOfClass:[NSDictionary class]]){ NSLog(@"NSDictionary"); NSDictionary *dic = jsonObject; NSLog(@"dic = %@",dic); } else if([jsonObject isKindOfClass:[NSArray class]]){ NSLog(@"NSDictionary"); NSDictionary *arr = jsonObject; NSLog(@"arr = %@",arr); } }];
(4)Request中帶有Json格式數據
//Request NSMutableURLRequest *urlRequest = [NSMutableURLRequest new]; [urlRequest setURL:[NSURL URLWithString:@"http://XXXX.sinaapp.com/test/test.php"]]; [urlRequest setTimeoutInterval:10.0f]; [urlRequest setHTTPMethod:@"POST"]; [urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData]; [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];//這句沒有也沒關係 NSDictionary *dicRequest = @{@"name":@"leo", @"id":@"456"}; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicRequest options:NSJSONWritingPrettyPrinted error:nil]; [urlRequest setHTTPBody:jsonData]; NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { NSError *err2 = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err2]; if([jsonObject isKindOfClass:[NSDictionary class]]){ NSLog(@"NSDictionary"); NSDictionary *dic = jsonObject; NSLog(@"dic = %@",dic); } else if([jsonObject isKindOfClass:[NSArray class]]){ NSLog(@"NSDictionary"); NSDictionary *arr = jsonObject; NSLog(@"arr = %@",arr); } }];
伺服器端的處理與返回(將request的值末尾加上_appending,然後返回)
<?php header('Access-Control-Allow-Origin:*'); $json_string = $GLOBALS['HTTP_RAW_POST_DATA']; $obj = json_decode($json_string); //echo $obj->name; //echo $obj->id; $arr = array( "name"=>$obj->name."_appending", "id"=>$obj->id."_appending"); echo json_encode($arr);
(5)從伺服器下載圖片(啟示就是普通的GET請求,只是將response中的data轉為Image而已)
//Request NSMutableURLRequest *urlRequest = [NSMutableURLRequest new]; [urlRequest setURL:[NSURL URLWithString:@"https://res.wx.qq.com/mpres/htmledition/images/pic/case-detail/nfhk_l23b6fe.jpg"]]; [urlRequest setTimeoutInterval:10.0f]; [urlRequest setHTTPMethod:@"GET"]; [urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { UIImage *img = [UIImage imageWithData:data]; [self.imgView setImage:img]; }];
(6)以上所有動作都可以使用代理來做,原理上都是一樣的
NSURLConnectionDataDelegate,
NSURLConnectionDelegate,
NSURLConnectionDownloadDelegate