ios - 如何使用 NSURLConnection 与 SSL 连接以获得不受信任的证书?

我有以下简单的代码来连接到 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 委托(delegate)中:

- (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(很多),在必要时向用户显示对话框等之后。

https://stackoverflow.com/questions/933331/

相关文章:

ios - 清除 NSUserDefaults

ios - UIImageView 在设备上的启动屏幕中缺少图像

objective-c - 将项目转换为使用 ARC 时, "switch case is in p

objective-c - NSDate 获取年/月/日

ios - 如何在 NSLog 中打印 bool 标志?

iphone - 我们如何以编程方式检测设备在哪个 iOS 版本上运行?

objective-c - 语义问题 : Property's synthesized getter

objective-c - 如何将堆栈跟踪打印到控制台/登录 Cocoa?

ios - 在 Swift 中实例化并展示一个 viewController

objective-c - Objective-C中强弱的区别