NSURLSession(网络会话)

GET请求方式一

    //1 获得NSURLSession对象(默认对象)---->默认开启异步
    NSURLSession *session = [NSURLSession sharedSession];
    //2 获取url
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"];
    //3 创建NSURLRequest请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //4 创建任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //data---->json
        
        id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        NSLog(@"获取的响应体数据:%@",json);
        
        NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        
        NSLog(@"获取的响应体数据:%@",dataStr);
        
        
        NSLog(@"获取的URL、状态编码和响应头数据%@",response);
        
        NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response;
        NSInteger statuCode = urlResponse.statusCode;
        NSLog(@"状态编码:%ld",statuCode);
        
        NSLog(@"错误的信息:%@",error);
        
        NSLog(@"------%@",[NSThread currentThread]);
        
    }];
    
    //5 恢复任务(恢复任务后,再回调执行block里的代码)
    [dataTask resume];
    

GET请求方式二

    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        
        NSLog(@"获取的响应体数据:%@",dataStr);
    }];
    
    [dataTask resume];

POST请求方式

    //1 获得NSURLSession对象
    NSURLSession *session = [NSURLSession sharedSession];
    //2 创建请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login"]];
    //2.1请求方式:默认是GET
    request.HTTPMethod = @"POST";
    //2.2请求体
    request.HTTPBody = [@"username=123&pwd=123"dataUsingEncoding:NSUTF8StringEncoding];
    //2.3缓存策略
    request.cachePolicy = NSURLRequestUseProtocolCachePolicy;
    //2.4设置超时时间
    request.timeoutInterval = 5;
    //2.5设置请求头
    [request setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"];
    //3 创建任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //data---->json
        
        id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        NSLog(@"获取的响应体数据:%@",json);
        
        NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        
        NSLog(@"获取的响应体数据:%@",dataStr);
        
        NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response;
        NSInteger statuCode = urlResponse.statusCode;
        NSLog(@"状态编码:%ld",statuCode);
        
        NSDictionary *headResponse = urlResponse.allHeaderFields;
        NSLog(@"获取的响应头数据%@",headResponse);
        
        NSLog(@"获取的URL、状态编码和响应头数据%@",response);
        
        //取得响应头中的信息项
        NSString *contentType = [urlResponse.allHeaderFields objectForKey:@"Content-Type"];
        NSLog(@"信息项:%@",contentType);
        
        
        NSLog(@"错误的信息:%@",error);
        
        NSLog(@"------%@",[NSThread currentThread]);
        
    }];
    
    //恢复任务
    [dataTask resume];

代理方式请求(这里用到了NSURLSessionConfiguration网络会话配置)

@interface ViewController ()<NSURLSessionDataDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    //设置缓存策略
    config.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
    //设置网络服务类型
    config.networkServiceType = NSURLNetworkServiceTypeDefault;
    //设置超时
    config.timeoutIntervalForRequest = 10;
    //设置请求头
    config.HTTPAdditionalHeaders = @{@"Accept-Language":@"zh-cn"};
    //设置后台请求,会把wifi、电量的可用性考虑在内
    config.discretionary = YES;
    //设置是否允许使用蜂窝数据
    config.allowsCellularAccess = YES;
    
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"];
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[[NSOperationQueue alloc]init] ];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url];
    
    [dataTask resume];
    
    
}

#pragma mark - <NSURLSessionDataDelegate>
/**
 * 1.接收到服务器的响应
 */

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    NSLog(@"%s", __func__);
    
    // 允许处理服务器的响应,才会继续接收服务器返回的数据
    completionHandler(NSURLSessionResponseAllow);
    
   
}

/**
 * 2.接收到服务器的数据(可能会被调用多次)
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"dataStr:%@",dataStr);
    NSLog(@"%s", __func__);
}

/**
 * 3.请求成功或者失败(如果失败,error有值)
 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    NSLog(@"%s", __func__);
}

网络请求简单下载


    
    // 获得NSURLSession对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    // 获得下载任务
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        // 文件将来存放的真实路径--->在沙盒cache里面存储文件
        NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        
        // 剪切location的临时文件到真实路径
        NSFileManager *mgr = [NSFileManager defaultManager];
        [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
    }];
    
    // 启动任务
    [task resume];
    

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • iOS开发系列--网络开发 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可...
    lichengjin阅读 3,739评论 2 7
  • 阅读目录 一、整体介绍 二、使用的一般步骤 三 举例 四 NSURLSessionConfiguration 附录...
    九洲仙人阅读 852评论 1 3
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,115评论 19 139
  • 在WWDC 2013中,Apple的团队对NSURLConnection进行了重构,并推出了NSURLSessio...
    lxl125z阅读 2,384评论 0 1
  • 目录 网络基本概念 TCP/IP协议簇基本概念 HTTP 网络开发技术解决方案 数据解析 网络优化 1. 网络基本...
    Ryan___阅读 1,386评论 1 0