我尝试使用NSURLDownload从带有自签名证书的Web服务器下载文件。这通常会导致:
NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9812)
或类似。
根据NSURLDownloadDelegate Protocol Reference,在认证期间应该调用以下方法:
- (BOOL)download:(NSURLDownload *)download canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
- (void)download:(NSURLDownload *)download didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
如其他SO答案中所述,这些方法可用于允许使用自签名证书。不幸的是,他们没有被召唤。
所有其他委托方法都按预期工作。
简化代码(这里看不多):
- (int)retrieve:(NSString *)urlString
{
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
downloadComplete = false;
downloadSucceeded = true;
NSURLDownload *download = [[NSURLDownload alloc] initWithRequest:theRequest delegate:self];
if (!download) {
fprintf(stderr, "Download failed\n");
}
while ((downloadComplete == false) && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
return (downloadSucceeded == true);
}
- (BOOL)download:(NSURLDownload *)download canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
NSLog(@"download:canAuthenticateAgainstProtectionSpace");
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)download:(NSURLDownload *)download didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSLog(@"download:didReceiveAuthenticationChallenge");
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
if([challenge.protectionSpace.host isEqualToString:@"myhost.mydomain.com"])
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
我通过废弃NSURLDownload
支持NSURLConnection
解决了这个问题,但我仍然想知道发生了什么。 (等效的NSURLConnectionDelegate
方法按预期调用。)
是否有人成功使用NSURLDownload
自签名证书?