内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我使用以下代码连接到使用了SSL的网页
NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url]; [ NSURLConnection sendSynchronousRequest: urlRequest returningResponse: nil error: &error ];
但如果证书是自签名证书,则会出现错误。Error Domain=NSURLErrorDomain Code=-1202 UserInfo=0xd29930 "untrusted server certificate".
是否有一种方法来设置接受连接(就像在浏览器中你可以点接受)或者绕过它?
有一个 API 可以实现这个。
把这样的东西添加到你的NSURLConnection
代理中:
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace { return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; } - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) if ([trustedHosts containsObject:challenge.protectionSpace.host]) [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; }
注意这里的connection:didReceiveAuthenticationChallenge:
如果需要,可以在向用户显示对话框之后,将其消息发送给 challenge 的 sender (更多),以此类推。