iOS AFNetWorking HTTPS自签名证书请求

首先后台会给你2个证书,一个是client.p12 ,另一个ca.cer,一般p12会包括.cer的信任,所以,我们只需导入p12到我们的项目中。

下面开始上代码,AFNetWorking 3.0,请求方式:Get


- (void)sendGetWithUrl:(NSString *)url callbackBlock:(void(^)(NSDictionary *))callback {

 

    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];

    securityPolicy.allowInvalidCertificates = YES;//是否允许使用自签名证书

    securityPolicy.validatesDomainName = NO;//是否需要验证域名

    

    NSString *urlStr = [Utils UTF8:url];


    AFHTTPSessionManager *afManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:SERVER_URL]];

    afManager.requestSerializer = [AFJSONRequestSerializer serializer];

    afManager.responseSerializer = [AFJSONResponseSerializer serializer];

    afManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain", nil];

    

    [afManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [afManager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];


 [afManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession * _Nonnull session, NSURLAuthenticationChallenge * _Nonnull challenge, NSURLCredential *__autoreleasing  _Nullable * _Nullable credential) {

        

        //选择质询认证的处理方式

        NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;

        __autoreleasing NSURLCredential *credent = nil;

        

        //NSURLAuthenticationMethodServerTrust质询认证方式

        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {

            //基于客户端的安全策略来决定是否信任该服务器,不信任则不响应质询

            if ([afManager.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {

                //创建质询证书

                credent = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];

                //确认质询方式

                if (credential) {

                    disposition = NSURLSessionAuthChallengeUseCredential;

                } else {

                    disposition = NSURLSessionAuthChallengePerformDefaultHandling;

                }

            } else {

                //取消质询

                disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;

            }

        } else {

            SecIdentityRef identity = NULL;

            SecTrustRef trust = NULL;

            NSString *p12 = [[NSBundle mainBundle]pathForResource:@"client" ofType:@"p12"];

            NSFileManager *fileManager = [NSFileManager defaultManager];

            if (![fileManager fileExistsAtPath:p12]){

                NSLog(@"client.p12:not exist");

            }else {

                NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12];

                

                if ([[self class]extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data])

                {

                    SecCertificateRef certificate = NULL;

                    SecIdentityCopyCertificate(identity, &certificate);

                    const void*certs[] = {certificate};

                    CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);

                    credent =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge  NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];

                    disposition =NSURLSessionAuthChallengeUseCredential;

                }

            }

        }

        

        return disposition;

    }];


 [afManager  GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {

        ;

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {


#ifdef DEBUG

        NSError *error = nil;

        NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:&error];

        NSString *resJson = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        NSLog(@"response %@ : %@",url,resJson);

#endif

        

        callback(responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSString *title;

        if ([self networkReachability]) {

            title = HintNetworkError;

        }else {

            title = @"网络连接失败";

        }

        [self initSVProgressHUDStyle];

        [SVProgressHUD showErrorWithStatus:title];

#ifdef DEBUG

        NSLog(@"response error %@ : %@",url,error);

#endif

        return;


//        callback(nil);


    }];


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值