我遇到的问题与这里的问题非常相似:Can I use NSURLCredentialStorage for HTTP Basic Authentication?
该问题的作者接受了答案,但后来发布说解决方案代码返回 NSURLErrorUserCancelledAuthentication
错误。我正在使用 DIGEST
身份验证,但除此之外我的代码正在执行相同的操作,并返回相同的错误。
我不想以明文形式发送用户名和密码,因此我绝对不想简单地将用户名和密码添加到 URL 的前面。有没有办法让 NSURLConnection 的 sendSynchronousRequest:returningResponse:error:
方法查阅共享的 NSURLCredentialStorage?这听起来像是类别适合做的事情,但我完全不知道如何做到这一点——听起来我必须完全重新实现 sendSynchronousRequest:returningResponse:error:
方法让它工作。
如何执行查询共享 NSURLCredentialStorage 的同步 URL 连接?
最佳答案
绝对可以。创建您的 NSURLCredential,并将其添加到 NSURLCredentialStorage 作为保护空间的默认。 示例:
// Permananent, session, whatever.
NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence: NSURLCredentialPersistencePermanent];
// Make sure that if the server you are accessing presents a realm, you set it here.
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:@"blah.com" port:0 protocol:@"http" realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
// Store it
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace];
此时,使用与您设置的保护空间相匹配的保护空间进行质询的任何后续 NSURLConnection 都将使用此凭据
关于iphone - 将 NSURLCredentialStorage 与同步 NSURLConnection 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3391976/