NSURLSession htpps证书设置

NSURLSession http转Https

1.设置代理

NSURLSession *sesson = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];

2.在代理方法中实现对证书的操作 


方法一:这是在开发者足够信任后端的安全的情况下做的,比如调个接口,这样做的结果就是忽略证书的验证,直接信任。

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{

    if([challenge.protectionSpace.authenticationMethodisEqualToString:NSURLAuthenticationMethodServerTrust]){//服务器信任证书

        

        NSURLCredential *credential = [NSURLCredentialcredentialForTrust:challenge.protectionSpace.serverTrust];//服务器信任证书

        if(completionHandler)

        completionHandler(NSURLSessionAuthChallengeUseCredential,credential);

    }

}

方法二:可以把证书加到工程中,然后https访问时在代理方法中进行证书的验证

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{

    

    SecTrustRef servertrust = challenge.protectionSpace.serverTrust;

    SecCertificateRef certi= SecTrustGetCertificateAtIndex(servertrust, 0);

    NSData *certidata = CFBridgingRelease(CFBridgingRetain(CFBridgingRelease(SecCertificateCopyData(certi))));

    NSString *path = [[NSBundle mainBundle] pathForResource:@"https" ofType:@"cer"];

    NSData *localCertiData = [NSData dataWithContentsOfFile:path];

    if ([certidata isEqualToData:localCertiData]) {

        NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:servertrust];

        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];

        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);

        NSLog(@"服务端证书认证通过");

    }else {

        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);

        NSLog(@"服务端认证失败");

    }

    

}


在北京的灯中,有一盏是我家的。这个梦何时可以实现?哪怕微微亮。北京就像魔鬼训练营,有能力的留,没能力的走……

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值