OC实现基本网络请求

NSURLSession使用

- (void) getRequest {
    NSURL *url = [NSURL URLWithString:@"xxxx"];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //response : 响应:服务器的响应
        //data:二进制数据:服务器返回的数据。(就是我们想要的内容)
        //error:链接错误的信息
        NSLog(@"网络响应:response:%@",response);
    }];
}

- (void) postRequest {
    NSURL *url = [NSURL URLWithString:@"xxxx"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSData *data = [NSJSONSerialization dataWithJSONObject:@{} options:NSJSONWritingPrettyPrinted error:nil];
    
    request.HTTPMethod = @"POST";
    request.HTTPBody = data;
    [request setValue:[NSString stringWithFormat:@"%ld", data.length] forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil){
            id respObj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@", respObj);
        }
    }];
}

AFNetworking 使用

一、导库

pod 'AFNetworking', '~> 4.0'

二、使用

GET请求

-(void)getRequest{
    NSString *urlString = @"";
    
    AFHTTPSessionManager *manger =[AFHTTPSessionManager manager];
    
    [manger GET:urlString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}

POST请求

-(void)postRequest{
    NSString *urlString = @"";
    
    AFHTTPSessionManager *manger =[AFHTTPSessionManager manager];
    
    NSMutableDictionary *parameter= @{@"":@"",@"":@""};
    
    [manger POST:urlString parameters:parameter progress:^(NSProgress * _NonnulluploadProgress){
        
    }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}

Download请求

-(void)downloadRequest{
    //1. 创建NSURLSessionConfiguration
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    //2. 创建管理者对象
    AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
    
    //3. 设置url
    NSURL *url = [NSURL URLWithString:@""];
    
    //4. 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //5. 下载任务
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //打印下载进度
        NSLog(@"%lf",1.0*downloadProgress.completedUnitCount/downloadProgress.totalUnitCount);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //设置下载路径
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager]URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        //下载完成
        NSLog(@"File downloaded to : %@",filePath);
    }];
    //启动任务
    [downloadTask resume];
}

Upload请求

//UpLoad请求
-(void)uploadRequest{
    //创建NSURLSessionConfiguration
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    //创建管理者对象
    AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
    
    //设置url
    NSURL *url = [NSURL URLWithString:@""];
    //创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //文件路径
    NSURL *filePath = [NSURL fileURLWithPath:@"file://Users/xxxxx"];
    
    //上传任务
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if(error){
            //错误
            NSLog(@"Error:%@",error);
        }else{
            //成功
            NSLog(@"Success %@ %@",response,responseObject);
        }
    }];
    //启动任务
    [uploadTask resume];
}
  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

倾云鹤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值