简体   繁体   English

结合使用NSURLCredentialStorage和同步NSURLConnection

[英]Using NSURLCredentialStorage with a synchronous NSURLConnection

I am having a problem very similar to this question here: Can I use NSURLCredentialStorage for HTTP Basic Authentication? 我遇到的问题与这里的问题非常相似: 我可以使用NSURLCredentialStorage进行HTTP基本身份验证吗?

The author of that question accepted an answer but later posted that the solution code was returning NSURLErrorUserCancelledAuthentication errors. 该问题的作者接受了一个答案,但后来发布了该解决方案代码返回了NSURLErrorUserCancelledAuthentication错误。 I am using DIGEST authentication, but otherwise my code is doing the same thing, and returns the same error. 我正在使用DIGEST身份验证,但否则我的代码将执行相同的操作,并返回相同的错误。

I do not want to send the username and password in cleartext, so I definitely don't want to simply tack the username and password onto the front of the URL. 我不想以明文形式发送用户名和密码,所以我绝对不想简单地将用户名和密码添加到URL的开头。 Is there some way to get NSURLConnection's sendSynchronousRequest:returningResponse:error: method to consult the shared NSURLCredentialStorage? 有什么方法可以获取NSURLConnection的sendSynchronousRequest:returningResponse:error:方法来查询共享的NSURLCredentialStorage吗? It sounds like the type of thing a category would be good for, but I haven't the faintest idea of how I would do it--it sounds like I'd have to completely reimplement the sendSynchronousRequest:returningResponse:error: method to get it to work. 这听起来似乎是类别的优点,但是我对如何执行此方法没有最模糊的想法-听起来我必须完全重新实现sendSynchronousRequest:returningResponse:error:方法来获取它起作用。

How can I perform a synchronous URL connection that consults the shared NSURLCredentialStorage? 如何执行查询共享NSURLCredentialStorage的同步URL连接?

Absolutely you can. 绝对可以。 Create your NSURLCredential, and add to NSURLCredentialStorage as the default for the protection space. 创建您的NSURLCredential,并将其添加到NSURLCredentialStorage作为保护空间的默认值 Example: 例:

// 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];

At this point, any subsequent NSURLConnection that is challenged using a protection space that matches what you set will use this credential 此时,任何后续的使用保护空间与您设置的内容相匹配的NSURLConnection都将使用此凭据

这可能无法完全回答您的问题,但是:通过NSURLConnection进行的同步抓取有很多问题(身份验证是至少一个问题),并且如果有可能,您应该真正地重组应用程序以使用异步API,这很可能不会您遇到有关身份验证的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM