• 源码0601-01-掌握-NSURLConnection-GET请求


    插件:SVProgressHUD

    //  ViewController.m
    //  01-掌握-NSURLConnection-GET请求
    #import "ViewController.h"
    #import <SVProgressHUD.h>
    
    @interface ViewController () <NSURLConnectionDataDelegate>
    @property (weak, nonatomic) IBOutlet UITextField *pwdField;
    
    @property (weak, nonatomic) IBOutlet UITextField *usernameField;
    
    /** 用来存放服务器返回的数据 */
    @property (nonatomic, strong) NSMutableData *responseData;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
        
    }
    
    - (IBAction)login {
        // 检测用户名
        NSString *username = self.usernameField.text;
        if (username.length == 0) {
            [SVProgressHUD showErrorWithStatus:self.usernameField.placeholder];
            return;
        }
        
        // 检测密码
        NSString *pwd = self.pwdField.text;
        if (pwd.length == 0) {
            [SVProgressHUD showErrorWithStatus:self.pwdField.placeholder];
            return;
        }
        
    //    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
        // 显示HUD
        [SVProgressHUD showWithStatus:@"哥在帮你登录中..." maskType:SVProgressHUDMaskTypeBlack];
        
        // 0.请求路径
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://120.25.226.186:32812/login?username=%@&pwd=%@", username, pwd]];
        
        // 1.创建请求对象
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        
        // 2.发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            // 3.解析服务器返回的数据(解析成字符串)
            NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            
            // 4.回到主线程
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                // 隐藏HUD
    //            [SVProgressHUD dismiss];
                
                // 显示一些提示信息
                NSUInteger loc = [string rangeOfString:@"":""].location + 3; //查字符在字符串中的位置;
                NSUInteger len = [string rangeOfString:@""}"].location - loc;
                NSString *msg = [string substringWithRange:NSMakeRange(loc, len)];//截取字符串,参数:给一个开始位置,截取的长度;
                if ([string containsString:@"success"]) {
                    [SVProgressHUD showSuccessWithStatus:msg];
                } else {
                    [SVProgressHUD showErrorWithStatus:msg];
                }
            }];
        }];
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        /** 发送一个GET请求给服务器 **/
        [self delegateAysnc];
    }
    
    - (void)delegateAysnc
    {
        // 0.请求路径
        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it"];
        
        // 1.创建请求对象
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        // 2.创建连接对象
    //    [[NSURLConnection alloc] initWithRequest:request delegate:self];
        
    //    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
    //    [conn start];
        
        [NSURLConnection connectionWithRequest:request delegate:self];
        
        // 取消
    //    [conn cancel];
    }
    
    #pragma mark - <NSURLConnectionDataDelegate> -- being
    /**
     * 接收到服务器的响应
     */
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        // 创建data对象
        self.responseData = [NSMutableData data];
        NSLog(@"didReceiveResponse");
    }
    
    
    /**
     * 接收到服务器的数据(如果数据量比较大,这个方法会被调用多次)
     */
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        // 不断拼接服务器返回的数据
        [self.responseData appendData:data];
        NSLog(@"didReceiveData -- %zd", data.length);
    }
    
    /**
     * 务器的数据成功接收完毕
     */
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        NSLog(@"connectionDidFinishLoading");
        NSString *string = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", string);
        
        self.responseData = nil;
    }
    
    /**
     * 请求失败(比如请求超时)
     */
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
        NSLog(@"didFailWithError -- %@", error);
    }
    #pragma mark - <NSURLConnectionDataDelegate> -- end
    /**
     * 发送异步请求
     */
    - (void)async
    {
        // 0.请求路径
        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it"];
        
        // 1.创建请求对象
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        // 2.发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            // 请求完毕会来到这个block
            // 3.解析服务器返回的数据(解析成字符串)
            NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@", string);
            //        NSHTTPURLResponse *r = (NSHTTPURLResponse *)response;
            //
            //        NSLog(@"%zd %@", r.statusCode, r.allHeaderFields);
        }];
    }
    
    /**
     * 发送同步请求
     */
    - (void)sync
    {
        // 0.请求路径
        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=345"];
        //    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/video"];
        
        // 1.创建请求对象
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        // 2.发送请求
        // sendSynchronousRequest阻塞式的方法,等待服务器返回数据
        
        NSHTTPURLResponse *response = nil;//服务器返回的信息要存放到这
        NSError *error = nil;//接收的错误信息,存放到这
        
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        
        // 3.解析服务器返回的数据(解析成字符串)
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@ %@", string, response.allHeaderFields);
    }
    
    @end
    02-掌握-NSURLConnection-POST请求
    //
    //  ViewController.m
    //  02-掌握-NSURLConnection-POST请求
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        // 1.请求路径
        NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
        
        // 2.创建请求
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        // 更改请求方法
        request.HTTPMethod = @"POST";
        // 设置请求体
        request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
        // 设置超时(5秒后超时)
        request.timeoutInterval = 5;
        // 设置请求头
    //    [request setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"];
        
        // 3.发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (connectionError) { // 比如请求超时
                NSLog(@"----请求失败");
            } else {
                NSLog(@"------%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            }
        }];
    }
    
    @end
    03-掌握-NSURLConnection-中文URL处理
    //  ViewController.m
    //  03-掌握-NSURLConnection-中文URL处理
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        [self post];
    }
    
    - (void)post
    {
        // 0.请求路径
        NSString *urlStr = @"http://120.25.226.186:32812/login2";
        NSURL *url = [NSURL URLWithString:urlStr];
        
        // 1.创建请求对象
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"POST";
        request.HTTPBody = [@"username=小码哥&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
        
        // 2.发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            // 3.解析服务器返回的数据(解析成字符串)
            NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@", string);
        }];
    }
    
    - (void)get
    {
        // 0.请求路径
        NSString *urlStr = @"http://120.25.226.186:32812/login2?username=小码哥&pwd=520it";
        // 将中文URL进行转码
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:urlStr];
        
        // 1.创建请求对象
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        // 2.发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            // 3.解析服务器返回的数据(解析成字符串)
            NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@", string);
        }];
    }
    
    @end
    本人无商业用途,仅仅是学习做个笔记,特别鸣谢小马哥,学习了IOS,另日语学习内容有需要文本和音频请关注公众号:riyuxuexishuji
  • 相关阅读:
    MySQL数据库高可用集群搭建-PXC集群部署
    高性能高并发网站架构,教你搭建Redis5缓存集群
    redis连接错误3种解决方案System Error MISCONF Redis is configured to save RDB snapshots
    进程异常行为-反弹Shell攻击,KILL多个进程
    Laravel中我们登录服务器通过 Tinker 手动创建后台管理用户
    Laravel5.x的php artisan migrate数据库迁移创建操作报错SQLSTATE[42000]解决
    Laravel:php artisan key:generate三种报错解决方案,修改默认PHP版本(宝塔面板)
    大型网站如何防止崩溃,解决高并发带来的问题
    PHP微信公众平台OAuth2.0网页授权,获取用户信息代码类封装demo(二)
    iOS开发 ReactiveCocoa入门教程 第二部分
  • 原文地址:https://www.cnblogs.com/laugh/p/6587964.html
Copyright © 2020-2023  润新知