小编典典

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

all

我有以下简单的代码来连接到 SSL 网页

NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
[ NSURLConnection sendSynchronousRequest: urlRequest returningResponse: nil error: &error ];

除了如果证书是自签名证书它会给出错误Error Domain=NSURLErrorDomain Code=-1202 UserInfo=0xd29930 "untrusted server certificate".有没有办法将它设置为无论如何都接受连接(就像在浏览器中你可以按接受一样)或绕过它的方法?


阅读 88

收藏
2022-04-20

共1个答案

小编典典

有一个支持的 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。

2022-04-20