使用NSURLSession进行get,post请求

195 阅读1分钟

在网络请求这块,要么是使用AFN,要么是用Alamofire. 最近想仿一下SD的图片请求,却发现,用NSURLSession的时候,磕磕碰碰的,不过还好,图片的请求还比较简单,如果是post,get请求呢? 下面的代码展示了一个简单的GET请求.

//Get request
    //get url
    NSString *getUrlString = @"http://localhost/~lirenqiang/Untitled%204.json";
    NSURL *getUrl = [NSURL URLWithString:getUrlString];
    //request
    NSURLRequest *getRequest = [NSURLRequest requestWithURL:getUrl];
    NSURLSession *session = [NSURLSession sharedSession];
    
    // create a get request task.
    NSURLSessionDataTask *getTask = [session dataTaskWithRequest:getRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        NSLog(@"%@", response); //请求头信息.
        NSError *getError; //序列化错误信息.
        //将data转成json数据
        NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&getError];
        if (!getError) {
            NSLog(@"json: %@", json);
        } else {
            NSLog(@"error: %@", getError);
        }
    }];
    // make task work
    [getTask resume];