1 GET請(qǐng)求
1,確定URL
NSURL *url = [NSURL URLWithString:@"xxx"];
2,創(chuàng)建請(qǐng)求對(duì)象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
3,獲得一個(gè)會(huì)話(huà)對(duì)象
NSURLSession *session = [NSURLSession sharedSession];
4.創(chuàng)建請(qǐng)求任務(wù)
//第一個(gè)參數(shù):請(qǐng)求對(duì)象
//第二個(gè)參數(shù):completionHandler 完成后執(zhí)行的回調(diào)
//data:響應(yīng)體
//response:響應(yīng)頭
//error:錯(cuò)誤信息
//!!!注意:默認(rèn)情況下completionHandler在子線(xiàn)程中調(diào)用
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable data, NSURLResponse * _Nullable response,
NSError * _Nullable error) {
//解析服務(wù)器返回的數(shù)據(jù)
}];
5,執(zhí)行任務(wù)
[dataTask resume];
2 POST請(qǐng)求
1,確定URL
NSURL *url = [NSURL URLWithString:@"xxx"];
2,創(chuàng)建可變請(qǐng)求對(duì)象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//修改請(qǐng)求方式為POST
request.HTTPMethod = @"POST";
//設(shè)置請(qǐng)求體
request.HTTPBody = [@"username=520it&pwd=520&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
3,獲得一個(gè)會(huì)話(huà)對(duì)象
NSURLSession *session = [NSURLSession sharedSession];
4.創(chuàng)建請(qǐng)求任務(wù)
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable data, NSURLResponse * _Nullable response,
NSError * _Nullable error) {
//解析服務(wù)器返回的數(shù)據(jù)
}];
5,執(zhí)行任務(wù)
[dataTask resume];
3 代理方法
1,確認(rèn)請(qǐng)求路徑
NSURL *url = [NSURL URLWithString:@"xxx"];
2,創(chuàng)建會(huì)話(huà)對(duì)象
NSURLSession *session = [NSURLSession sessionWithConfiguration:
[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
3,創(chuàng)建任務(wù)Task
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url];
4,執(zhí)行Task
[dataTask resume];
5,-----代理-----
//當(dāng)接收到服務(wù)器響應(yīng)的時(shí)候調(diào)用
//默認(rèn)情況下是不會(huì)接收服務(wù)器返回?cái)?shù)據(jù)的,如果需要接收應(yīng)該主動(dòng)告訴系統(tǒng)
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
NSLog(@"didReceiveResponse");
/*
NSURLSessionResponseCancel = 0, 取消(默認(rèn)的做法)
NSURLSessionResponseAllow = 1, 允許(接收數(shù)據(jù))
NSURLSessionResponseBecomeDownload = 2,
NSURLSessionResponseBecomeStream NS_ENUM_AVAILABLE(10_11, 9_0) = 3,
*/
completionHandler(NSURLSessionResponseAllow);
}
//當(dāng)接收到服務(wù)器返回?cái)?shù)據(jù)的時(shí)候調(diào)用(會(huì)調(diào)用多次)
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data
{
NSLog(@"didReceiveData");
[self.resultData appendData:data];
}
//當(dāng)請(qǐng)求完成或者是失敗的時(shí)候調(diào)用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
NSLog(@"didCompleteWithError");
//解析數(shù)據(jù)
NSLog(@"%@",[[NSString alloc]initWithData:self.resultData encoding:NSUTF8StringEncoding]);
}