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
        -  本次拒绝,下次再试






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值