我正在与服务器通信,该服务器验证密码并返回无效密码的 401 错误,以及指定失败尝试次数的 json 正文。每次验证失败时,服务器都会增加该数字。
我面临的问题是,当 NSURLConnection 收到 401 响应时,它会启动涉及这些委托方法的身份验证机制:
连接:canAuthenticateAgainstProtectionSpace:
连接:didReceiveAuthenticationChallenge:
如果我在可以验证方法,将发出新的相同请求。这将导致服务器第二次增加失败的尝试次数(这显然是不希望的),并且我将得到 401 响应(连接:didReceiveResponse:)
如果我在可以验证方法,那么didReceiveAuthenticationChallenge方法被调用。如果我想停止第二个请求,我可以打电话[challenge.sender cancelAuthenticationChallenge:challenge]。但如果我这样做,我不会收到 401 响应,而是收到错误。
我找不到捕获第一个 401 响应的方法。有什么办法可以做到这一点吗?
1)对于没有客户端证书的普通 SSL,您不需要实现这 2 种方法
2) 如果您仍然想要,您应该检查 [challenge failure Response] 对象中的 HTTP 响应代码:
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSURLCredential *urlCredential = [challenge proposedCredential];
NSURLResponse *response = [challenge failureResponse];
int httpStatusCode = -1;
if(response != nil) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
httpStatusCode = [httpResponse statusCode];
}
if(urlCredential != nil || httpStatusCode == 401) {
//wrong username or more precisely password, call this to create 401 error
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
else {
//go ahead, load SSL client certificate or do other things to proceed
}
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return YES;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)