ios-信任服务器证书

当我们使用https去进行网络请求的时候,都会收到服务器给我们的证书,而这些证书有分为机构认证的证书,也有是自己签发的证书。在ios中如果我们是去请求的有机构认证的去发送https的请求,就不需要去做处理,但是如果是自签证书,我们必须要去做处理,否则的话是拿不到数据的。所以我们需要在一个代理方法中进行处理

//首先创建Session   NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] 
delegate:self delegateQueue:[NSOperationQueue mainQueue]];//生成任务NSURLSessionDataTask * task = [session dataTaskWithURL:[NSURL URLWithString:@"https://www.apple.com"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);}];//执行任务[task resume];
在下面这个代理方法中进行处理,下面的challenge.protectionSpace表示的是一个安全的空间。

-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:
(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{//1.判断服务器的采用的认证方法的方法是否是:信任服务器证书if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {//2.创建身份验证证书NSURLCredential * credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];//3.进行处理if(completionHandler){   //UseCredential表示的是使用服务器发回的证书completionHandler(NSURLSessionAuthChallengeUseCredential,credential);}}}
其中关于NSURLSessionAuthChallengeDisposition是一个枚举有以下的枚举值

 NSURLSessionAuthChallengeDisposition (处置):NSURLSessionAuthChallengeUseCredential                     -  使用服务器发回证书(保存在challenge里面)NSURLSessionAuthChallengePerformDefaultHandling-  默认处理方式,会忽略证书NSURLSessionAuthChallengeCancelAuthenticationChallenge-  取消整个请求,忽略证书NSURLSessionAuthChallengeRejectProtectionSpace-  本次拒绝,下次再试







本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部