GET請求方式一
//1 獲得NSURLSession對象(默認(rèn)對象)---->默認(rèn)開啟異步
NSURLSession *session = [NSURLSession sharedSession];
//2 獲取url
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"];
//3 創(chuàng)建NSURLRequest請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//4 創(chuàng)建任務(wù)
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//data---->json
id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"獲取的響應(yīng)體數(shù)據(jù):%@",json);
NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"獲取的響應(yīng)體數(shù)據(jù):%@",dataStr);
NSLog(@"獲取的URL却舀、狀態(tài)編碼和響應(yīng)頭數(shù)據(jù)%@",response);
NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response;
NSInteger statuCode = urlResponse.statusCode;
NSLog(@"狀態(tài)編碼:%ld",statuCode);
NSLog(@"錯誤的信息:%@",error);
NSLog(@"------%@",[NSThread currentThread]);
}];
//5 恢復(fù)任務(wù)(恢復(fù)任務(wù)后,再回調(diào)執(zhí)行block里的代碼)
[dataTask resume];
GET請求方式二
NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"獲取的響應(yīng)體數(shù)據(jù):%@",dataStr);
}];
[dataTask resume];
POST請求方式
//1 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
//2 創(chuàng)建請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login"]];
//2.1請求方式:默認(rèn)是GET
request.HTTPMethod = @"POST";
//2.2請求體
request.HTTPBody = [@"username=123&pwd=123"dataUsingEncoding:NSUTF8StringEncoding];
//2.3緩存策略
request.cachePolicy = NSURLRequestUseProtocolCachePolicy;
//2.4設(shè)置超時時間
request.timeoutInterval = 5;
//2.5設(shè)置請求頭
[request setValue:@"zh-cn" forHTTPHeaderField:@"Accept-Language"];
//3 創(chuàng)建任務(wù)
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//data---->json
id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"獲取的響應(yīng)體數(shù)據(jù):%@",json);
NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"獲取的響應(yīng)體數(shù)據(jù):%@",dataStr);
NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response;
NSInteger statuCode = urlResponse.statusCode;
NSLog(@"狀態(tài)編碼:%ld",statuCode);
NSDictionary *headResponse = urlResponse.allHeaderFields;
NSLog(@"獲取的響應(yīng)頭數(shù)據(jù)%@",headResponse);
NSLog(@"獲取的URL、狀態(tài)編碼和響應(yīng)頭數(shù)據(jù)%@",response);
//取得響應(yīng)頭中的信息項(xiàng)
NSString *contentType = [urlResponse.allHeaderFields objectForKey:@"Content-Type"];
NSLog(@"信息項(xiàng):%@",contentType);
NSLog(@"錯誤的信息:%@",error);
NSLog(@"------%@",[NSThread currentThread]);
}];
//恢復(fù)任務(wù)
[dataTask resume];
代理方式請求(這里用到了NSURLSessionConfiguration網(wǎng)絡(luò)會話配置)
@interface ViewController ()<NSURLSessionDataDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
//設(shè)置緩存策略
config.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
//設(shè)置網(wǎng)絡(luò)服務(wù)類型
config.networkServiceType = NSURLNetworkServiceTypeDefault;
//設(shè)置超時
config.timeoutIntervalForRequest = 10;
//設(shè)置請求頭
config.HTTPAdditionalHeaders = @{@"Accept-Language":@"zh-cn"};
//設(shè)置后臺請求歌溉,會把wifi焰枢、電量的可用性考慮在內(nèi)
config.discretionary = YES;
//設(shè)置是否允許使用蜂窩數(shù)據(jù)
config.allowsCellularAccess = YES;
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[[NSOperationQueue alloc]init] ];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url];
[dataTask resume];
}
#pragma mark - <NSURLSessionDataDelegate>
/**
* 1.接收到服務(wù)器的響應(yīng)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
NSLog(@"%s", __func__);
// 允許處理服務(wù)器的響應(yīng)童擎,才會繼續(xù)接收服務(wù)器返回的數(shù)據(jù)
completionHandler(NSURLSessionResponseAllow);
}
/**
* 2.接收到服務(wù)器的數(shù)據(jù)(可能會被調(diào)用多次)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"dataStr:%@",dataStr);
NSLog(@"%s", __func__);
}
/**
* 3.請求成功或者失斆薨病(如果失敗,error有值)
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"%s", __func__);
}
網(wǎng)絡(luò)請求簡單下載
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 獲得下載任務(wù)
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
// 文件將來存放的真實(shí)路徑--->在沙盒cache里面存儲文件
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
// 剪切l(wèi)ocation的臨時文件到真實(shí)路徑
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}];
// 啟動任務(wù)
[task resume];