- - (void)viewDidLoad {
- [super viewDidLoad];
- // Do any additional setup after loading the view from its nib.
- /*
- https原理:
- 1,客戶端請求服務器,如果是第一次請求,服務器返回向客戶端返回證書
- 2,客戶端需要處理是否同意安裝證書,如果同意安裝,以後的所有通信都需要用這個證書來加密。(手機端需要自動處理證書)
- 3,服務器拿到數據以後,利用自己的私鑰解密數據。(數據只有私鑰才能解密)
- */
- //1,不帶證書的請求,有時候不用安裝,原因有二:可能以前裝過,或者有些大網站不用安裝
- // NSURLSessionTask *task = [[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:@"https://developer.apple.com/"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
- // //
- //
- // NSLog(@"error:%@",error);
- // NSLog(@"data:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
- // }];
- // [task resume];
- //2,程序自動安裝證書的方式
- NSURLSession *sesson = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
- NSURLSessionTask *task = [sesson dataTaskWithURL:[NSURL URLWithString:@"https://xxx/json"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
- //
- NSLog(@"error:%@",error);
- NSLog(@"data:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
- }];
- [task resume];
- }
- #pragma mark -----NSURLSessionTaskDelegate-----
- //NSURLAuthenticationChallenge 中的protectionSpace對象存放了服務器返回的證書信息
- //如何處理證書?(使用、忽略、拒絕。。)
- - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler//通過調用block,來告訴NSURLSession要不要收到這個證書
- {
- //(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
- //NSURLSessionAuthChallengeDisposition (枚舉)如何處理這個證書
- //NSURLCredential 授權
- //證書分爲好幾種:服務器信任的證書、輸入密碼的證書 。。,所以這裏最好判斷
- if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){//服務器信任證書
- NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];//服務器信任證書
- if(completionHandler)
- completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
- }
- NSLog(@"....completionHandler---:%@",challenge.protectionSpace.authenticationMethod);
- }
利用NSURLSession實現https請求
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.