我正在与服务器通信,该服务器验证密码并返回无效密码的 401 错误,以及指定失败尝试次数的 json 正文。每次验证失败时,服务器都会增加该数字。
我面临的问题是,当 NSURLConnection 收到 401 响应时,它会启动涉及这些委托(delegate)方法的身份验证机制:
connection:canAuthenticateAgainstProtectionSpace:
connection:didReceiveAuthenticationChallenge:
如果我在 canAuthenticate 方法中返回 NO,则会发出新的相同请求。这将导致服务器第二次增加失败的尝试次数(这显然是不希望的),并且我将收到 401 响应 (connection:didReceiveResponse:)
如果我在 canAuthenticate 方法中返回 YES,则调用 didReceiveAuthenticationChallenge 方法。如果我想停止第二个请求,我可以调用[challenge.sender cancelAuthenticationChallenge:challenge]。但如果我这样做,我不会收到 401 响应,而是收到错误。
我找不到捕获第一个 401 响应的方法。有什么办法可以做到吗?
最佳答案
1) 对于没有客户端证书的普通 SSL,您不需要实现这 2 种方法
2) 如果您仍然想要,您应该检查 [challenge failureResponse] 对象中的 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;
}
关于ios - NSURLConnection 在 401 状态下重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13944527/