美文网首页iOS Developer
网络编程—NSURLConnection

网络编程—NSURLConnection

作者: 小白文_Vincent | 来源:发表于2016-12-21 15:58 被阅读0次
文艺求关注.png

<h5>NSURLConnection的使用步骤</h5>

  • 使用NSURLConnection发送请求的步骤很简单
    • 创建一个NSURL对象,设置请求路径
    • 传入NSURL创建一个NSURLRequest对象,设置请求头和请求体
    • 使用NSURLConnection发送请求
NSURLConnection的使用步骤.png
  • <h5>NSURLConnection发送请求</h5>
  • NSURLConnection常见的发送请求方法有以下几种(同步一种,异步两种)
    • <b>同步请求(GET)</b>
- (void)sendSynchronousRequestByVtc {

    /**
     GET:http://120.25.226.186:32812/login?username=123&pwd=456&type=JSON
     协议+主机地址+接口名称+?+参数1&参数2&。。。
     post:http://120.25.226.186:32812/login
     协议+主机地址+接口名称
     */
    // GET,没有请求体
    // 01.确认请求路径
    NSURL *url = [NSURL URLWithString:@""];
    // 02.创建请求对象
    // 请求头不需要设置(默认的请求头)
    // 默认的请求方法 ----> GET请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 真实类型:NSHTTPURLResponse
    //    NSURLResponse *response = nil;
    NSHTTPURLResponse *response = nil;
    
    /**
     // 03.发同步请求送请求
     @param NSURLRequest 请求对象
     @param NSURLResponse 响应头信息(地址)
     @param NSError 错误信息
     @return 响应体信息
     */
    // 同步网络请求,阻塞
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    // 04.解析 data --> 字符串  NSUTF8StringEncoding:固定一般都传这个
    NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    
    // 如何获取状态码
    NSLog(@"%zd", response.statusCode);  
}
  • <b>异步请求(GET):</b>根据对服务器返回数据的处理方式不同,可以分为两种
    ▽ Block回调
- (void)sendAsynchronousRequestByVtc {

    // 01.确认请求路径
    NSURL *url = [NSURL URLWithString:@""];
    // 02.创建请求对象
    // 请求头不需要设置(默认的请求头)
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLResponse *response = nil;
    /**
     // 03.发送异步请求

     @param NSURLRequest 请求对象
     @param NSOperationQueue 队列 决定completionHandler代码块的调用线程
     @param completionHandler 当请求完成(成功/失败)的时候回调
        response:响应头
        data:响应体
        connectionError:错误信息
     @return
     */
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        // 04.解析数据
        NSLog(@"%zd", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        
        // 获取状态码
        NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
        NSLog(@"%zd", res.statusCode);
    }];
}

▽ 代理

...<NSURLConnectionDataDelegate>  // 遵守代理协议
@property (nonatomic, strong) NSMutableData *resultData;

#pragma mark- lazy loading
- (NSMutableData *)resultData {

    if (_resultData == nil) {
        _resultData = [NSMutableData data];
    }
    return _resultData;
}
#pragma mark- event
- (void)deledateToSendRequest {
    
    // 01.确定请求路径
    NSURL *url = [NSURL URLWithString:@""];
    
    // 02.创建请求对象
    // 请求头不需要设置(默认请求头)
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 03.设置代理,发送请求
    // 3.1第一种设置代理的方法
    [NSURLConnection connectionWithRequest:request delegate:self];
    // 3.2第二种设置代理的方法
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    /**
     // 3.3第三种设置代理的方法 
        设置代理,并不会设置发送请求(startImmediately == YES,才会发送请求,如果是NO,需要调用开启方法)

     @param NSURLRequest 请求对象
     @param delegate 代理
     @param startImmediately 是否发送请求
     @return NSURLConnection
     */
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
    
    // 调用开始方法
    [connection start];
    
//    [connection cancel];    //取消
}
#pragma mark- NSURLConnectionDelegate
// 01 当接受到服务器响应的时候调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    
    NSLog(@"%s", __func__);
}
// 02 接收到服务器返回数据的时候调用 会调用多次
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    NSLog(@"%s", __func__);
    // 拼接数据
    [self.resultData appendData:data];
}
// 03 当请求失败的时候调用
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

    NSLog(@"%s", __func__);
}
// 04 请求结束的时候,调用该方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSLog(@"%s", __func__);
    
    // 解析数据
    NSLog(@"%@", [[NSString alloc] initWithData:self.resultData encoding:NSUTF8StringEncoding]);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

<b>* 注意:如上方法都是发送GET请求的方法,如需发送POST请求,有些注意点需要大家注意</b>

  • 需设置可变请求对象
  • 需手动修改请求方式
  • 需手动设置请求体信息
  • 。。。。。。
- (void)sendAsynchronousRequestWithPost {

    // 01.确定请求路径
    NSURL *url = [NSURL URLWithString:@""];
    // 02.设置可变请求对象
    NSMutableURLRequest *mutableURLRequest = [NSMutableURLRequest requestWithURL:url];
    // 03.修改请求方式,POST必须大写
    mutableURLRequest.HTTPMethod = @"POST";
    // 设置属性,请求超时
    mutableURLRequest.timeoutInterval = 10;
    // 设置请求头User-Agent(此属性主要给后台人员看)
    [mutableURLRequest setValue:@"可自定义输入" forHTTPHeaderField:@"User-Agent"];
    // 04.设置请求体信息,字符串---> NSData
    mutableURLRequest.HTTPBody = [@"username=123&pwd=123&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
    // 05.发送异步请求
    [NSURLConnection sendAsynchronousRequest:mutableURLRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        // 06.解析数据,NSData -----> NSString
        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);      
    }];
}

<b>补充:关于URL中有中文的处理方式</b>

  • 我们在开发中有可能会遇到URL中有中文的现象,而如果URL有中文,我们在开发的时候,需要手动去URL中文转码,否则URL会显示为空并且报错
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    NSString *urlStr = @"http://120.27.225.186:32812/login2?username=新科技&pwd=123&type=JSON";
    // 中文转码处理
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // 01.设置请求路径
    NSURL *url = [NSURL URLWithString:urlStr];
    
    // 02.设置请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 03.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        // 容错处理
        if (connectionError) {
            return ;
        }
        // 04.解析
        NSLog(@"%@", connectionError);
    }];
}

<b>* 注意:如果是发送POST请求,则不需要在转码,如上方法只限制与发送GET请求时使用</b>
如上方法,解析数据的方法了解即可,一般在开发中,不会如此繁琐的去解析数据,开发中,最常用的解析数据的方法一般有JSON或者XML方法


关注一下又不会怀孕.png

相关文章

网友评论

    本文标题:网络编程—NSURLConnection

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