zoukankan      html  css  js  c++  java
  • iOS开发 GET、POST请求方法:NSURLConnection篇

    Web Service使用的主要协议是HTTP协议,即超文本传输协议。

    HTTP/1.1协议共定义了8种请求方法(OPTIONS、HEAD、GET、POST、PUT、DELETE、TRACE、CONNECT)作为Web服务器。

    GET方法,是向指定的资源发送请求,请求的参数“显式”地在URL的后面。有点像明信片,把内容“显式”写在外面,因此安全性比较差。一般使用于读取数据、例如从服务器读取静态图片、或查询数据等。

    POST方法,是向指定资源提交数据,请求服务器进行处理,数据包含在请求体中。参数和地址分开,放在body里面。有点像把信内容放在信封中,接触的人看不到,安全性比较高。一般用于例如提交表单、上传文件等(请求的的动态资源,与查询类似,每个方法调用都要传递很多参数,因此需要使用 NSMutableURLRequest创建请求。 )

    iOS SDK中为HTTP请求提供了同步和异步请求这两种不同的API,

    同步请求,可以从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作,意味着线程阻塞;

    异步请求,不会阻塞主线程,而会建立一个新的线程来操作,用户发出异步请求后,依然可以对UI进行操作,程序可以继续运行;

    它们的主要区别在于连接方式的不同。

    下面通过请求一个登陆接口介绍有关于网络请求中的不同情况。

    一、GET方法

    1.同步get方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    //1.创建一个web路径
    NSString *webPath=[NSString stringWithFormat:@"http://172.16.2.254/php/phonelogin?name=%@&pass=%@&btn=login",yourname,yourpass];
    webPath = [webPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //url不允许为中文等特殊字符,需要进行字符串的转码为URL字符串,例如空格转换后为“%20”;
    NSURL *url=[NSURL URLWithString:webPath];
    //2.根据WEB路径创建一个请求
    NSURLRequest  *request=[NSURLRequest requestWithURL:url];
    NSURLResponse *respone;//获取连接的响应信息,可以为nil
    NSError *error;        //获取连接的错误时的信息,可以为nil
    //3.得到服务器数据
    NSData  *data=[NSURLConnection sendSynchronousRequest:request returningResponse:respone error:&error];
    if(data==nil)
    {
    NSLog(@"登陆失败:%@,请重试",error);
    return;
    }
    /*
    4.对服务器获取的数据data进行相应的处理;
    */
    //1.创建一个web路径
    NSString *webPath=[NSString stringWithFormat:@"http://172.16.2.254/php/phonelogin?name=%@&pass=%@&btn=login",yourname,yourpass];
    webPath = [webPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //url不允许为中文等特殊字符,需要进行字符串的转码为URL字符串,例如空格转换后为“%20”;
    NSURL *url=[NSURL URLWithString:webPath];
    //2.根据WEB路径创建一个请求
    NSURLRequest  *request=[NSURLRequest requestWithURL:url];
    NSURLResponse *respone;//获取连接的响应信息,可以为nil
    NSError *error;        //获取连接的错误时的信息,可以为nil
    //3.得到服务器数据
    NSData  *data=[NSURLConnection sendSynchronousRequest:request returningResponse:respone error:&error];
    if(data==nil)
    {
    NSLog(@"登陆失败:%@,请重试",error);
    return;
    }
    /*
    4.对服务器获取的数据data进行相应的处理;
    */

    2.异步get方法:

    异步请求与同步请求的不同在于使用NSURLConnectionDataDelegate委托协议,指定代理.

    1
    2
    3
    4
    5
    6
    @interface ViewController : UIViewController // 遵循协议
    @property (weak,nonatomic) NSMutableData *receiveData;  //创建一个可变data,用于异步接收服务器的数据
    @end
    @interface ViewController : UIViewController // 遵循协议
    @property (weak,nonatomic) NSMutableData *receiveData;  //创建一个可变data,用于异步接收服务器的数据
    @end

    创建网络请求:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    //1.创建一个web路径
    NSString  *webPath=[NSString stringWithFormat: @"http://172.16.2.254/php/phonelogin?name=%@&pass=%@&btn=login",yourname,yourpass];
    webPath = [webPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL  *url=[NSURL URLWithString:webPath];
    //2.根据WEB路径创建一个请求
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //3.指定代理 以异步的方式接收数据NSURLConnectionDataDelegate
    NSURLConnection  *con=[NSURLConnection connectionWithRequest:request delegate:self];
    if(con==nil)
    {
    NSLog(@"创建连接失败.");
    return;
    }
    else//成功 准备接数据
    {
    if(self.receiveData==nil)
    {
    self.receiveData=[[NSMutableData alloc] init];
    }
    }
    //1.创建一个web路径
    NSString  *webPath=[NSString stringWithFormat: @"http://172.16.2.254/php/phonelogin?name=%@&pass=%@&btn=login",yourname,yourpass];
    webPath = [webPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL  *url=[NSURL URLWithString:webPath];
    //2.根据WEB路径创建一个请求
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //3.指定代理 以异步的方式接收数据NSURLConnectionDataDelegate
    NSURLConnection  *con=[NSURLConnection connectionWithRequest:request delegate:self];
    if(con==nil)
    {
    NSLog(@"创建连接失败.");
    return;
    }
    else//成功 准备接数据
    {
    if(self.receiveData==nil)
    {
    self.receiveData=[[NSMutableData alloc] init];
    }
    }

    异步的代理行为:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
    NSLog(@"已经响应成功.");   //清空 为当前连接做准备
    self.receiveData.length=0;
    }
    -(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
    NSLog(@"已经接收到了数据.");
    //追加接收到的数据
    [self.receiveData appendData:data];
    }
    -(void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
    NSLog(@"接收数据已经完成.");
    /*
    对服务器获取的数据receiveData进行相应的处理;
    */
    }
    -(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
    NSLog(@"连接失败.");
    }
    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
    NSLog(@"已经响应成功.");   //清空 为当前连接做准备
    self.receiveData.length=0;
    }
    -(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
    NSLog(@"已经接收到了数据.");
    //追加接收到的数据
    [self.receiveData appendData:data];
    }
    -(void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
    NSLog(@"接收数据已经完成.");
    /*
    对服务器获取的数据receiveData进行相应的处理;
    */
    }
    -(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
    NSLog(@"连接失败.");
    }

    二、POST方法

    1.同步post方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    //1.创建一个web路径
    webPath = [webPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url=[NSURL URLWithString:webPath];
    //2.建立一个带协议缓存类型的请求 (使用NSMutableURLRequest,是post方法的关键)
    NSMutableURLRequest  *request=[NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10];
    //3.设置表单提交的方法(默认为get)
    [request setHTTPMethod:@"post"];
    //4.设置要提交的参数
    NSString  *args=[NSString stringWithFormat:@"uname=%@&upas=%@&btn=login",uname,upas];
    [request setHTTPBody:[args dataUsingEncoding:NSUTF8StringEncoding]];
    NSData *recvData=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(recvData!=nil)
    {     /*        对服务器获取的数据recvData进行相应的处理     */    }       else    {          NSLog(@"连接失败,请重试!");    }
    //1.创建一个web路径
    webPath = [webPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url=[NSURL URLWithString:webPath];
    //2.建立一个带协议缓存类型的请求 (使用NSMutableURLRequest,是post方法的关键)
    NSMutableURLRequest  *request=[NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10];
    //3.设置表单提交的方法(默认为get)
    [request setHTTPMethod:@"post"];
    //4.设置要提交的参数
    NSString  *args=[NSString stringWithFormat:@"uname=%@&upas=%@&btn=login",uname,upas];
    [request setHTTPBody:[args dataUsingEncoding:NSUTF8StringEncoding]];
    NSData *recvData=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(recvData!=nil)
    {     /*        对服务器获取的数据recvData进行相应的处理     */    }       else    {          NSLog(@"连接失败,请重试!");    }

    2.post方法的异步与同步的区别在于使用NSURLConnectionDataDelegate委托协议,指定代理.

    这一点与get方法一致,所以就不进行长篇幅的演示了。

    以上就是关于部分网络同步异步请求,get、post请求方法的演示,由于UI控件还有其他的处理没有附上,具体的读者可以进行相应细节的调整,进行完整的网络请求项目开发。

    由于iOS 9开始,引入了新的网络接口NSURLSession,而在iOS9中NSURLConnection被宣布弃用,因此关于NSURLSession发送GET和POST请求的资料部分,有兴趣的可以参考:《iOS开发 GET、POST请求方法(NSURLSession篇)

  • 相关阅读:
    2020软件工程作业02
    自我介绍
    Requests的使用
    爬虫基本原理
    2019春总结作业
    十二周作业
    十一周作业
    第十周作业
    intellij idea 的全局搜索快捷键方法
    Oracle多表关联
  • 原文地址:https://www.cnblogs.com/guiyangxueyuan/p/5567161.html
Copyright © 2011-2022 走看看