zoukankan      html  css  js  c++  java
  • 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.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){//服务器信任证书

            

            NSURLCredential *credential = [NSURLCredential credentialForTrust: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(@"服务端认证失败");

        }

        

    }

  • 相关阅读:
    SQLServer 2008数据库查看死锁、堵塞的SQL语句
    Jmeter(三)简单的HTTP请求(非录制)
    watir中不能打开页面中的URL超链接解决办法
    我要搬博客到这里来,请协助
    Jmeter(一)精简测试脚本
    性能测试机中存在大量的TIME_WAIT状态的连接,影响并发压力的发起
    ruby+watir随机而不重复获取Menu菜单的元素
    Eclipse中安装Ruby的插件org.rubypeople.rdt
    TCP连接各状态数量、以及TCP各状态变迁流程
    ruby+watirwatir3.0上实现快照/截图
  • 原文地址:https://www.cnblogs.com/huangzs/p/8183089.html
Copyright © 2011-2022 走看看