基本网络请求

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];
}

你可能感兴趣的:(IOS,objective-c,ios)