[iOS]网络请求中的证书验证-NSURLConnection

记录一下在网络请求中证书验证的基于NSURLConnection的实现

一.开始一个请求

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //保存数据
    self.data = [NSMutableData data];
    
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://XXXXXXXXXXXX"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:240];
    [request setHTTPMethod:@"POST"];
    [request setHTTPShouldHandleCookies:YES];
    NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData *postData = [@"XX=XX&XX=XX" dataUsingEncoding:gbkEncoding];
    [request setHTTPBody:postData];

    self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}

二.实现NSURLConnection验证的回调方法

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    
    if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
        SecTrustRef trust = challenge.protectionSpace.serverTrust;
        SecTrustResultType result;
        
        //获取本地证书
        NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"XXX" ofType:@"cer"]];
        SecCertificateRef certificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(data));
        
        SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef)@[CFBridgingRelease(certificate)]);
        OSStatus status = SecTrustEvaluate(trust, &result);
        
        
        if (status == errSecSuccess &&
            (result == kSecTrustResultProceed ||
             result == kSecTrustResultUnspecified)) {
                
                //验证成功,生成NSURLCredential凭证cred,告知challenge的sender使用这个凭证来继续连接
                NSURLCredential *cred = [NSURLCredential credentialForTrust:trust];
                [challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
                
            } else {
                
                //验证失败,取消这次验证流程
                [challenge.sender cancelAuthenticationChallenge:challenge];
                
            }
    }
}

三.接收数据

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.data appendData:data];
}

四.处理数据

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString *retStr = [[NSString alloc] initWithData:self.data encoding:enc];
    NSLog(@"retString:%@",retStr);
    NSData* newData=[retStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    id responseObject = [NSJSONSerialization JSONObjectWithData:newData options:NSJSONReadingMutableLeaves error:&error];
    if (error) {
        NSLog(@"error:%@",error);
    }
    if (responseObject) {
        NSLog(@"%@", responseObject);
    }else{
        
    }
}

推荐阅读更多精彩内容

  • AFHTTPRequestOperationManager 网络传输协议UDP、TCP、Http、Socket、X...
    Carden阅读 2,019评论 0 12
  • 在 WWDC 16 中,Apple 表示, 从 2017年1月1日起(最新消息, 实施时间已延期),所有新提交的 ...
    kmplayer阅读 674评论 0 5
  • iOS网络架构讨论梳理整理中。。。 其实如果没有APIManager这一层是没法使用delegate的,毕竟多个单...
    yhtang阅读 2,926评论 1 21
  • 恍若 已隔三秋 飞絮轻吻着大地 夏蝉尚未高歌 几许飞燕 啄春泥 栖于檐下 尚不知 三秋于你 又是 何般感受 是刹那...
    呦呦鹿鸣m阅读 21评论 0 4
  • 1.感谢电饭煲,做出美味的腊八粥。谢谢,谢谢,谢谢! 2.感谢妈妈婆婆喝我做的腊八粥,心里暖暖的。谢谢,谢谢,谢谢...
    上官祯莜2016阅读 19评论 0 0