使用 NSURLConnection 连接HTTPS站点,需要处理SSL认证, NSURLConnectionDelegate 中定义了一些方法来处理认证
- – connection:canAuthenticateAgainstProtectionSpace:
- – connection:didReceiveAuthenticationChallenge:
一. NSURLConnection 中处理SSL
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace{ return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; }
如果接受任何证书
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{ [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; }
如果使用证书验证
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { static CFArrayRef certs; if (!certs) { NSData*certData =[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"srca" ofType:@"cer"]]; SecCertificateRef rootcert =SecCertificateCreateWithData(kCFAllocatorDefault,CFBridgingRetain(certData)); const void *array[1] = { rootcert }; certs = CFArrayCreate(NULL, array, 1, &kCFTypeArrayCallBacks); CFRelease(rootcert); // for completeness, really does not matter } SecTrustRef trust = [[challenge protectionSpace] serverTrust]; int err; SecTrustResultType trustResult = 0; err = SecTrustSetAnchorCertificates(trust, certs); if (err == noErr) { err = SecTrustEvaluate(trust,&trustResult); } CFRelease(trust); BOOL trusted = (err == noErr) && ((trustResult == kSecTrustResultProceed)||(trustResult == kSecTrustResultConfirm) || (trustResult == kSecTrustResultUnspecified)); if (trusted) { [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; }else{ [challenge.sender cancelAuthenticationChallenge:challenge]; } }
二. AFNetworking 框架中处理SSL
使用 AFURLConnectionOperation 类的下面两个方法,分别将上述代码以block方式传入即可。
– setAuthenticationAgainstProtectionSpaceBlock:
– setAuthenticationChallengeBlock:参考:
Technical Note TN2232 – HTTPS Server Trust Evaluation
NSURLConnection Class Reference
NSURLConnectionDelegate Protocol Reference
How to use NSURLConnection to connect with SSL for an untrusted cert?
NSURLConnection with Self-Signed Certificates
iPhone SSL based NSURLConnection with your own root cert
dhoerl / MyWebFetcher.m
https://github.com/AFNetworking/AFNetworking/
AFNetworking – AFURLConnectionOperation Class Reference
关于在UIwebView中访问HTTPS站点的几种方法