天天看點

利用NSURLSession實作https請求

  1. - (void)viewDidLoad {  
  2.     [super viewDidLoad];  
  3.     // Do any additional setup after loading the view from its nib.  
  4.    //1,不帶證書的請求,有時候不用安裝,原因有二:可能以前裝過,或者有些大網站不用安裝  
  5. //    NSURLSessionTask *task = [[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:@"https://developer.apple.com/"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {  
  6. //        //  
  7. //          
  8. //        NSLog(@"error:%@",error);  
  9. //        NSLog(@"data:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);  
  10. //    }];  
  11. //    [task resume];  
  12.     //2,程式自動安裝證書的方式  
  13.     NSURLSession *sesson = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];  
  14.     NSURLSessionTask *task = [sesson dataTaskWithURL:[NSURL URLWithString:@"https://xxx/json"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {  
  15.         //  
  16.         NSLog(@"error:%@",error);  
  17.         NSLog(@"data:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);  
  18.     }];  
  19.     [task resume];  
  20. }  
  21. #pragma mark -----NSURLSessionTaskDelegate-----  
  22. //NSURLAuthenticationChallenge 中的protectionSpace對象存放了伺服器傳回的證書資訊  
  23. //如何處理證書?(使用、忽略、拒絕。。)  
  24. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler//通過調用block,來告訴NSURLSession要不要收到這個證書  
  25. {  
  26.    //(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler  
  27.     //NSURLSessionAuthChallengeDisposition (枚舉)如何處理這個證書  
  28.     //NSURLCredential 授權  
  29.     //證書分為好幾種:伺服器信任的證書、輸入密碼的證書  。。,是以這裡最好判斷  
  30.     if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){//伺服器信任證書  
  31.         NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];//伺服器信任證書  
  32.         if(completionHandler)  
  33.            completionHandler(NSURLSessionAuthChallengeUseCredential,credential);  
  34.     }  
  35.     NSLog(@"....completionHandler---:%@",challenge.protectionSpace.authenticationMethod);  
  36. }  

繼續閱讀