天天看点

利用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. }  

继续阅读