2

我正在尝试使用 NSURLDownload 从具有自签名证书的 Web 服务器下载文件。这通常会导致:

NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9812)

或类似的。

根据NSURLDownloadDelegate 协议参考,在身份验证期间应该调用以下方法:

- (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自签名证书?

4

0 回答 0