NSURLConnection的使用

一: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

 

 

 

 

 

 

 

 

 

posted @ 2016-03-16 21:11  东方春  阅读(508)  评论(0编辑  收藏  举报