NSURLSession的基本使用(发送网络请求)

1 GET请求

1,确定URL

NSURL *url = [NSURL URLWithString:@"xxx"];

2,创建请求对象

NSURLRequest *request = [NSURLRequest requestWithURL:url];

3,获得一个会话对象

NSURLSession *session = [NSURLSession sharedSession];

4.创建请求任务

//第一个参数:请求对象
//第二个参数:completionHandler 完成后执行的回调
            //data:响应体
            //response:响应头
            //error:错误信息
//!!!注意:默认情况下completionHandler在子线程中调用
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable data, NSURLResponse * _Nullable response,
 NSError * _Nullable error) {
//解析服务器返回的数据
}];

5,执行任务

[dataTask resume];

2 POST请求

1,确定URL

NSURL *url = [NSURL URLWithString:@"xxx"];

2,创建可变请求对象

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//修改请求方式为POST
request.HTTPMethod = @"POST"; 
//设置请求体
request.HTTPBody = [@"username=520it&pwd=520&type=JSON" dataUsingEncoding:NSUTF8StringEncoding]; 

3,获得一个会话对象

NSURLSession *session = [NSURLSession sharedSession];

4.创建请求任务

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable data, NSURLResponse * _Nullable response, 
NSError * _Nullable error) {
//解析服务器返回的数据
}];

5,执行任务

[dataTask resume];

3 代理方法

1,确认请求路径

NSURL *url = [NSURL URLWithString:@"xxx"];

2,创建会话对象

NSURLSession *session = [NSURLSession sessionWithConfiguration:
[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];

3,创建任务Task

NSURLSessionDataTask *dataTask =  [session dataTaskWithURL:url];

4,执行Task

[dataTask resume];

5,-----代理-----

//当接收到服务器响应的时候调用
//默认情况下是不会接收服务器返回数据的,如果需要接收应该主动告诉系统
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask 
didReceiveResponse:(NSURLResponse *)response 
completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    NSLog(@"didReceiveResponse");
    /*
     NSURLSessionResponseCancel = 0,     取消(默认的做法)
    NSURLSessionResponseAllow = 1,      允许(接收数据)
    NSURLSessionResponseBecomeDownload = 2,
    NSURLSessionResponseBecomeStream NS_ENUM_AVAILABLE(10_11, 9_0) = 3,
     */
    completionHandler(NSURLSessionResponseAllow);
}

//当接收到服务器返回数据的时候调用(会调用多次)
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask 
didReceiveData:(NSData *)data
{
    NSLog(@"didReceiveData");
    [self.resultData appendData:data];
}

//当请求完成或者是失败的时候调用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task 
didCompleteWithError:(NSError *)error
{
     NSLog(@"didCompleteWithError");
    
    //解析数据
    NSLog(@"%@",[[NSString alloc]initWithData:self.resultData encoding:NSUTF8StringEncoding]);
}

你可能感兴趣的:(NSURLSession的基本使用(发送网络请求))