欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

ios开发网络篇—Get请求和Post请求 - 转

程序员文章站 2022-04-10 14:36:15
简单说明:建议提交用户的隐私数据一定要使用Post请求 相对Post请求而言,Get请求的所有参数都直接暴露在URL中,请求的URL一般会记录在服务器的访问日志中,而服务器的访问日志是黑客攻击的重点对象之一 用户的隐私数据如登录密码,银行帐号等 示例代码 ......

简单说明:建议提交用户的隐私数据一定要使用post请求 
相对post请求而言,get请求的所有参数都直接暴露在url中,请求的url一般会记录在服务器的访问日志中,而服务器的访问日志是黑客攻击的重点对象之一 
用户的隐私数据如登录密码,银行帐号等

示例代码

#define current_screen_width     [uiscreen mainscreen].bounds.size.width
#define current_screen_height     ([uiscreen mainscreen].bounds.size.height - 64)
#define button_width     80
#define button_height    40

@interface viewcontroller ()
//get 请求
@property(nonatomic,strong) uibutton *getbutton;
//post 请求
@property(nonatomic,strong) uibutton *postbutton;
@end

@implementation viewcontroller

- (void)viewdidload {
    [super viewdidload];
    
    _getbutton = [[uibutton alloc] initwithframe:cgrectmake(current_screen_width/2 - button_width/2,
                                                             current_screen_height/2 - button_height,
                                                             button_width,
                                                             button_height)];
    [_getbutton settitle:@"get 请求" forstate:uicontrolstatenormal];
    [_getbutton settitlecolor:[uicolor redcolor] forstate:uicontrolstatenormal];
    [_getbutton addtarget:self
                    action:@selector(getclick)
          forcontrolevents:uicontroleventtouchupinside];
    [self.view addsubview:_getbutton];
    
    _postbutton = [[uibutton alloc] initwithframe:cgrectmake(current_screen_width/2 - button_width/2,
                                                             _getbutton.frame.origin.y + _getbutton.frame.size.height + 60,
                                                             button_width,
                                                             button_height)];
    [_postbutton settitle:@"post 请求" forstate:uicontrolstatenormal];
    [_postbutton settitlecolor:[uicolor redcolor] forstate:uicontrolstatenormal];
    [_postbutton addtarget:self
                    action:@selector(postclick)
          forcontrolevents:uicontroleventtouchupinside];
    [self.view addsubview:_postbutton];
}

/* get 请求 */
-(void)getclick{
    //请求 url
    nsstring* urlstr = [nsstring stringwithformat:@"https://m.che168.com/beijing/?pvareaid=%d",110100];
    //封装成 nsurl
    nsurl* url = [nsurl urlwithstring:urlstr];

    //初始化 请求对象
    nsurlrequest* request = [[nsurlrequest alloc] initwithurl:url];
    //也可以这样初始化对象
    //nsurlrequest* request = [nsurlrequest requestwithurl:url];
    
    //发送请求  默认为 get 请求
    //1 、获得会话对象
    nsurlsession *session = [nsurlsession sharedsession];
    // 2、第一个参数:请求对象
    //      第二个参数:completionhandler回调(请求完成【成功|失败】的回调)
    //      data:响应体信息(期望的数据)
    //      response:响应头信息,主要是对服务器端的描述
    //      error:错误信息,如果请求失败,则error有值
    nsurlsessiondatatask *datatask = [session datataskwithrequest:request completionhandler:^(nsdata * _nullable data, nsurlresponse * _nullable response, nserror * _nullable error) {
        if(!error){
            nslog(@"请求加载成功。。。");
            //说明:(此处返回的数据是json格式的,因此使用nsjsonserialization进行反序列化处理)
            // nsdictionary *dict = [nsjsonserialization jsonobjectwithdata:data options:kniloptions error:nil];
            //如果是字符串则直接取出
            nsstring *str = [[nsstring alloc] initwithdata:data encoding:nsutf8stringencoding];
            nslog(@"get 请求返回的结果是:%@",[str substringtoindex: 300]);
        }
    }];
    //执行任务
    [datatask resume];
    
    /* ------------ ios9 之前请求方法,之后改成 nsurlsession 请求  --------------
    [nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue mainqueue] completionhandler:^(nsurlresponse * _nullable response, nsdata * _nullable data, nserror * _nullable connectionerror) {
        if(!connectionerror){
            nslog(@"加载成功。。。");
            nsstring *str = [[nsstring alloc] initwithdata:data encoding:nsutf8stringencoding];
            nslog(@"加载的内容是:%@",[str substringtoindex:200]);
        }else{
            nslog(@"加载失败");
        }
    }];
    */
}


/* post 请求 */
-(void)postclick{
    nsstring *urlstr = [nsstring stringwithformat:@"https://m.che168.com/"];
    //转码
    // stringbyaddingpercentescapesusingencoding 只对 `#%^{}[]|\"<> 加空格共14个字符编码,不包括”&?”等符号), ios9将淘汰
    // ios9 以后要换成 stringbyaddingpercentencodingwithallowedcharacters 这个方法进行转码
    urlstr = [urlstr stringbyaddingpercentencodingwithallowedcharacters:[[nscharacterset charactersetwithcharactersinstring:@"?!@#$^&%*+,:;='\"`<>()[]{}/\\| "] invertedset]];
    nsurl *url = [nsurl urlwithstring:urlstr];
    
    //创建会话对象
    nsurlsession *session = [nsurlsession sharedsession];
    
    //创建请求对象
    nsmutableurlrequest *request =[[nsmutableurlrequest alloc] initwithurl:url];
    [request sethttpmethod:@"post"];
    [request sethttpbody:[@"a=1&b=2&c=3&type=json" datausingencoding:nsutf8stringencoding]];
    
    //根据会话对象创建一个 task(发送请求)
    nsurlsessiondatatask* datatask = [session datataskwithrequest:request completionhandler:^(nsdata * _nullable data, nsurlresponse * _nullable response, nserror * _nullable error) {
        if(!error){
            //8.解析数据
            // nsdictionary *dict = [nsjsonserialization jsonobjectwithdata:data options:kniloptions error:nil];
            // nslog(@"%@",dict);
            nsstring *str = [[nsstring alloc] initwithdata:data encoding:nsutf8stringencoding];
            nslog(@"post 加载的内容是:%@",[str substringtoindex:200]);
        }else{
            nslog(@"请求发生错误:%@", [error description]);
        }
    }];
    [datatask resume]; //执行任务
}