zoukankan      html  css  js  c++  java
  • [IOS]

    NSURLConnection 是 苹果官网库中自带的简单网络请求的一个类,主要提供了使用URL创建同步和异步请求的方法,NSURLConnection-API

    简单介绍一下NSURLConnection 的使用方法

    使用NSURLConnection 发送GET同步请求

    // 1. 创建URL对象
    NSURL *url = [NSURL URLWithString:@"http://mock.allhome.com.cn/mock/5cf76e16de83be001011e63c/0605/header"];
    // 2. 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 3. 发送同步请求 参数1:请求对象 参数2:响应头信息 参数3:错误信息
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    // 打印返回数据
    NSLog(@"data:%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);    
    

    上边的运行结果输出如下图

    使用NSURLConnection 发送GET异步请求

    // 1. 创建URL对象
    NSURL *url = [NSURL URLWithString:@"http://mock.allhome.com.cn/mock/5cf76e16de83be001011e63c/0605/header"];
    // 2. 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 3. 发送异步请求 参数1:请求对象 参数2:请求执行的任务队列 参数3:回调方法
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
       // 参数1: 响应头信息,参数2:响应体信息  参数3:错误信息
       NSLog(@"响应头:%@", response);
       NSLog(@"响应体:%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
       NSLog(@"错误信息:%@", connectionError);
    }];
    

    上边的运行结果输出如下图

    使用NSURLConnection 发送POST请求

    // 1. 创建URL对象
    NSURL* postUrl = [NSURL URLWithString:@"http://mock.allhome.com.cn/mock/5cf76e16de83be001011e63c/0605/list"];
    // 2. 创建请求对象
    NSMutableURLRequest* postRequest = [NSMutableURLRequest requestWithURL:postUrl];
    [postRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [postRequest setHTTPMethod:@"POST"];
    NSDictionary* body = @{@"page":@"1",@"size":@"10"};
    postRequest.HTTPBody = [NSJSONSerialization dataWithJSONObject:body options:NSJSONWritingPrettyPrinted error:nil];
    // 6.3 发送POST请求
    NSData* data = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:nil error:nil];
    NSLog(@"data = %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    

    上边的运行结果输出如下图

    一般情况下NSURLConnection就像上边这些使用方式(还有一种通过代理处理数据的方式),但是在项目中一般不会直接使用NSURLConnection作为网络请求的选择

    NSURLSession 也是苹果官方提供用类,包含了下载数据和上传数据并可以在程序未运行是执行后台下载的任务。NSURLSessiion-Api

    简单介绍一下NSURLSession 的使用方法

    使用NSURLSession 发送GET同步请求

    // 1. 创建URL对象
    NSURL *url = [NSURL URLWithString:@"http://mock.allhome.com.cn/mock/5cf76e16de83be001011e63c/0605/header"];
    // 2. 创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    // 3. 创建数据请求任务
    NSURLSessionDataTask* task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"data:%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    // 4. 执行任务
    [task resume];
    

    上面代码执行后输出如下:

    发送POST请求其实也是差不多通过设置请求对象的相关属性,然后使用NSURLSession用请求对象去创建任务,然后获得任务对象调用其执行方法,还有一些上传、下载的方法看看API试一试就行了,下边主要介绍一下AFNetworking

    AFNetworking 是 IOS 网络三方库,主要是对NSURLConnection和NSURLSession的二次封装,是项目中使用最频繁的模块

    AFNetworking 主要包含几个主要模块:

    1. AFURLRequestSerialization
    2. AFURLResponseSerialization
    3. AFURLSessionManager
    4. AFHTTPSessionManager

    下面简单介绍一下他们的使用方法

    使用AFHTTPSessionManager 发送GET请求

    // 1. 创建AFHTTPSessionManager 对象
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    // 2. 发送GET请求
    [manager GET:@"http://mock.allhome.com.cn/mock/5cf76e16de83be001011e63c/0605/header" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"下载进度:任务总量:%lld 已完成任务:%lld",downloadProgress.totalUnitCount, downloadProgress.completedUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"返回数据: %@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"发生错误了: %@", error);
    }];
    

    执行后返回信息如下图所示

    使用AFHTTPSessionManager 发送POST请求

    // 1. 创建会话配置对象
    NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
    // 2. 创建会话管理对象
    AFHTTPSessionManager* manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:config];
    NSDictionary* params = @{@"page":@1,@"size":@10};
    // 3. 创建POST请求任务
    NSURLSessionDataTask* task = [manager POST:@"http://mock.allhome.com.cn/mock/5cf76e16de83be001011e63c/0605/list" parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"任务总量:%lld 已完成任务:%lld",uploadProgress.totalUnitCount, uploadProgress.completedUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"返回数据:%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"返回错误:%@", error);
    }];
    // 4. 开启任务
    [task resume];
    

    执行后返回信息如下图所示

    AFURLSessionManager 下载文件

    // 创建会话配置对象
    NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
    // 创建会话代理
    AFURLSessionManager* manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
    // 下载URL
    NSURL* url = [NSURL URLWithString:@"https://images.cnitblog.com/blog/497279/201311/29223500-176eb123446f463d8b118dd93e0e7d9b.png"];
    // 创建url请求对象
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    // 创建下载任务
    NSURLSessionDownloadTask* task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSLog(@"%@ %@", targetPath, response.suggestedFilename);
        NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
        NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];// URLWithString返回的是网络的URL,如果使用本地URL,需要注意
        NSURL *fileURL1 = [NSURL URLWithString:path];
        NSURL *fileURL = [NSURL fileURLWithPath:path];
        NSLog(@"== %@ |||| %@", fileURL1, fileURL);
        return fileURL;
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"%@ %@", filePath, error);
    }];
    // 开启下载任务
    [task resume];
    

    执行后效果如下图

    AFURLSessionManager 上传文件

    // sessionConfig 对象
    NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
    // 1. 创建AFURLSessionManager对象
    AFURLSessionManager* manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
    // 创建请求对象
    NSURL* url = [NSURL URLWithString:@"http://mock.allhome.com.cn/mock/5cf76e16de83be001011e63c/0605"];
    NSURLRequest* request = [[NSURLRequest alloc] initWithURL:url];
    // 本地图片地址
    NSURL* fileURL = [NSURL fileURLWithPath: @"/Users/wrp/Desktop/logo.png"];
    // 2. 创建上传文件任务
    NSURLSessionUploadTask* task = [manager uploadTaskWithRequest:request fromFile:fileURL progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"上传进度:%lld, %lld", uploadProgress.totalUnitCount, uploadProgress.completedUnitCount);
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSLog(@"响应数据:%@", responseObject);
        NSLog(@"错误消息:%@", error);
    }];
    // 3. 执行上传任务
    [task resume];
    

    执行后显示如下

  • 相关阅读:
    shell script 学习笔记-----标准输出
    《TCP/IP详解 卷一》读书笔记-----TCP persist &Keeplive timer
    《TCP/IP详解 卷一》读书笔记-----TCP超时重传
    《TCP/IP详解 卷一》读书笔记-----TCP数据流
    《TCP/IP详解 卷一》读书笔记-----TCP连接建立
    《TCP/IP详解 卷一》读书笔记-----DNS
    《TCP/IP详解 卷一》读书笔记-----广播&多播&IGMP
    《TCP/IP详解 卷一》读书笔记-----UDP&IP 分片
    《TCP/IP详解 卷一》读书笔记-----动态路由协议
    《TCP/IP 详解 卷一》读书笔记-----IP静态 路由
  • 原文地址:https://www.cnblogs.com/wrup/p/11110952.html
Copyright © 2011-2022 走看看