美文网首页
iOS原生网络请求

iOS原生网络请求

作者: 浪高达 | 来源:发表于2017-12-13 07:35 被阅读12次
    - (void)postLogin {
        /**
          POST请求参数格式 username=zhangsan&password=zhang
            但是不是在URL中拼接
         */
        // 1. NSURL
        NSURL *url = [NSURL URLWithString:@"http://localhost/login.php"];
        
        // 2. 创建请求
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        
        // 2.1 设置请求方法为POST
        request.HTTPMethod = @"POST";
        // 2.2  拼接参数
        NSString *params = [NSString stringWithFormat:@"username=%@&password=%@",self.username,self.password];
        
        // 2.2.1 把字符串转成二进制数据
        NSData *paramsData = [params dataUsingEncoding:NSUTF8StringEncoding];
        
        // 2.3 设置POST的参数,设置在请求体中
        [request setHTTPBody:paramsData];
        
        // 3. 发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            NSLog(@"%@",response);
            // 解析JSON
            id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSLog(@"%@",result);
        }];
    }
    
    - (void)getLogin {
        // GET登录
        /**
         1. GET通过URL拼接参数
         2. 在路径后面添加一个 ?
         3. 参数形式 参数名=参数值
         4. 多个参数之间,使用 & 来连接
         
         到工作中,URL可能不是.php,也有可能.action,do,jsp,asp....... 跟我们iOS开发没有关系
         后台给的url是什么就是写什么,不需要再去添加后缀
         
         如果URL中出现中文或者空格,需要做特殊处理, 百分号编码
         为了避免出现中文而导致程序崩溃,不管有没有中文,我们都要进行百分号转码
         在工作中,项目名,文件名,文件夹名字,建议不要使用中文命名
         */
        // 0. 拼接URL和参数
        NSString *urlString = [NSString stringWithFormat:@"http://localhost/login.php?username=%@&password=%@",self.username, self.password];
        // 如果URL中出现中文或者空格,需要做特殊处理, 百分号编码
        // iOS9 之后已经过期
        //   urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        // iOS 7 就存在的,不用担心版本问题
        urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        // 1. 创建URL - 如果URL中有中文,把字符串转成URL就会变为nil
        NSURL *url = [NSURL URLWithString:urlString];
        
        // 2. 创建请求
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        // 3. 发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            NSLog(@"%@",response);
            id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSLog(@"%@",result);
        }];
    
    }
    

    相关文章

      网友评论

          本文标题:iOS原生网络请求

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