我遇到了一个与这个问题非常相似的问题:Can I use NSURLCredentialStorage for HTTP Basic Authentication?
这个问题的作者接受了一个答案,但后来发布了解决方案代码返回NSURLErrorUserCancelledAuthentication错误。我使用的是DIGEST身份验证,但是我的代码也在做同样的事情,并且返回相同的错误。
我不想以明文形式发送用户名和密码,因此我绝对不想简单地将用户名和密码添加到URL的前面。有什么方法可以让NSURLConnection的sendSynchronousRequest:returningResponse:error:方法来查询共享NSURLCredentialStorage吗?这听起来像是一个类别所适合的类型,但是我一点也不知道该如何做--听起来我必须完全重新实现sendSynchronousRequest:returningResponse:error:方法才能使它工作。
如何执行咨询共享NSURLCredentialStorage的同步URL连接?
发布于 2010-08-05 17:02:35
这可能不能完全回答你的问题,但是:通过NSURLConnection的同步获取有很多问题(身份验证是最小的一个),如果可能的话,你真的应该重构你的应用程序来使用异步API,这很可能不会有你看到的关于身份验证的问题。
发布于 2013-02-14 06:37:07
你完全可以做到。创建您的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都将使用此凭据
https://stackoverflow.com/questions/3391976
复制相似问题