您的位置:首页 > 理论基础 > 计算机网络

iOS之使用NSURLConnection连接HTTPS(SSL)站点

2015-01-19 12:49 369 查看
转载自:http://www.tuicool.com/articles/7FnIZv

使用 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站点的几种方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS NSURLConnection SSL
相关文章推荐