IOS原生访问网络-NSURLSession

/**
 *  原生请求网络
 *
 *  @param method "POST"/"GET"
 *  @param para   请求参数
 *  @param url    请求地址
 */
- (void)connectToNetWithMethod:(NSString *)method andPara:(id)para andUrl:(NSString *)url {
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:20];
    [request setHTTPMethod:method];//method ="POST"/"GET"
    NSData *paraData  = [NSJSONSerialization dataWithJSONObject:para
                                                              options:NSJSONWritingPrettyPrinted
                                                                error:nil];
    [request setHTTPBody:paraData]; //把参数体放进去
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
        NSLog(@"apiJsonResult = %@",result);
        if (response) {
            //获取请求header返回的东西-示例Response-Id
            NSHTTPURLResponse* newResp = (NSHTTPURLResponse*)response;
            NSString *responseId = [newResp.allHeaderFields objectForKey:@"Response-Id"];
            //返回的内容 data

        }else{
            
        }
        
        
    }];
    [task resume];
}

你可能感兴趣的:(IOS原生访问网络-NSURLSession)