美文网首页
iOS网络请求总结、GET、POST、同步、异步代码块、异步代理

iOS网络请求总结、GET、POST、同步、异步代码块、异步代理

作者: 子键_北京不眠夜 | 来源:发表于2016-02-16 16:19 被阅读537次

    首先需要明白,GET跟POST 区别: 

    GET请求  ,将参数直接写在访问路径上。操作简单,不过容易被外界看到,安全性不高,地址最多255字节;POST请求,将参数放到body里面。

    POST请求操作相对复杂,需要将参数和地址分开,不过安全性高,参数放在body里面,不易被捕获

    同步 跟 异步区别:同步请求可以从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作,异步请求不会阻塞主线程,而会建立一个新的线程来操作,用户发出异步请求后,依然可以对UI进行操作,程序可以继续运行

    以下分别介绍几种方式的使用:

    1.GET 同步请求   

     //创建请求路径    

    NSString *strURL = [NSString stringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?act=register&r_type=1&email=%@&password=%@&user_name=%@",@"123456@qq.com",@"123456",@"zhangsan"];    

    //通过url创建网络请求    

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];    

    NSError *error =nil;    

    //同步方式连接服务器    

    NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:&error];   

     //json 解析返回数据   

     NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:kNilOptionserror:nil];  

      NSLog(@"%@",[dicobjectForKey:@"info"]);

    2.post 同步请求   

     //通过url创建网络请求    

    NSString *strURL = [NSStringstringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?"];    //通过url创建网络请求    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:strURL]];   

     //设置请求方式也POST(默认是GET)   

     [request setHTTPMethod:@"POST"];    

    //设置请求参数    NSString *body = [NSStringstringWithFormat:@"act=%@&r_type=%d&email=%@&password=%@&user_name=%@",@"register",1,@"12345@qq.com",@"123456",@"lisi"];   

     //需要NSUTF8StringEncoding转码    [request setHTTPBody:[bodydataUsingEncoding:NSUTF8StringEncoding]];   

     //同步方式连接服务器    NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:nil];    

    //json 解析返回数据    NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:kNilOptionserror:nil];    NSLog(@"%@",[dicobjectForKey:@"info"]);

    3.GET 异步代码块请求   

     NSString *strURL = [NSString stringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?act=register&r_type=1&email=%@&password=%@&user_name=%@",@"123456@qq.com",@"123456",@"zhangsan"];   

     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];    

    NSError *error = nil;    

    NSLog(@"111==%@",[NSThread currentThread]);    

    //创建异步代码方式   

     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {        NSLog(@"222==%@",[NSThread currentThread]);        

    //网络请求结束        

    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];      

      NSLog(@"%@",[dic objectForKey:@"info"]);               

     //回到主线程,去刷新界面//        

    self performSelectorOnMainThread:<#(SEL)#> withObject:<#(id)#> waitUntilDone:<#(BOOL)#>                dispatch_async(dispatch_get_main_queue(), ^{            //回主线程要做的事情        });      }];

    4.POST 异步代码块请求    

    NSString *strURL = [NSStringstringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?"];    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:strURL]];    

    [request setHTTPMethod:@"POST"];  

      [request setTimeoutInterval:10];   

     NSString *body = [NSStringstringWithFormat:@"act=%@&r_type=%d&email=%@&password=%@&user_name=%@",@"register",1,@"12345@qq.com",@"123456",@"lisi"];    

    [request setHTTPBody:[bodydataUsingEncoding:NSUTF8StringEncoding]];    [NSURLConnectionsendAsynchronousRequest:request queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *response,NSData *data, NSError *connectionError) {        NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:kNilOptionserror:nil];        NSLog(@"%@",[dicobjectForKey:@"info"]);    }];

    5. 异步代理请求用代理需要导入协议:NSURLConnectionDataDelegate@interface ViewController ()NSString *strURL = [NSString stringWithFormat:@"http://192.168.10.252/upload/mapi/index.php?"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]];

    [request setHTTPMethod:@"POST"];

    NSString *body = [NSString stringWithFormat:@"act=%@&r_type=%d&email=%@&password=%@&user_name=%@",@"register",1,@"12345@qq.com",@"123456",@"lisi"];

    [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];

    //使用代理的方式做网络请求

    [NSURLConnection connectionWithRequest:request delegate:self];

    #pragma mark -- 网络请求代理方法实现

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

    {

    NSLog(@"网络请求总数据量,这个只执行一次");

    infoData = [[NSMutableData alloc]init];

    }

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

    {

    NSLog(@"这个方法会执行多次!");

    [infoData appendData:data];

    }

    -(void)connectionDidFinishLoading:(NSURLConnection *)connection

    {

    NSLog(@"网络请求结束!!!");

    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:infoData options:kNilOptions error:nil];

    NSLog(@"%@",dict);

    NSLog(@"%@",dict[@"info"]);

    }

    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

    {

    NSLog(@"网络请求失败。失败原因%@",error);

    }

    相关文章

      网友评论

          本文标题:iOS网络请求总结、GET、POST、同步、异步代码块、异步代理

          本文链接:https://www.haomeiwen.com/subject/hxnpkttx.html