iPhone – NTLM,基本和其他授权使用asynchronousNSURLConnection

这是一个问题:我需要实现HTTP基本授权和MS NTLM授权。 我使用asynchronousNSURLConnection,所以我收到

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 

回电话。 这个方法的完整代码如下所示:

 -(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { NSString* authMethod = [[challenge protectionSpace] authenticationMethod]; NSLog(@"Authentication method: %@", authMethod); NSString *userName = self.login; if ([authMethod isEqualToString:NSURLAuthenticationMethodNTLM]) { userName = [userName lastElementAfterSlash]; } else if ([authMethod isEqualToString:NSURLAuthenticationMethodNegotiate]) { userName = [NSString stringWithFormat:@"%@@%@", userName, self.url.host]; } if ([challenge previousFailureCount] <= 1) { NSURLCredential *credential = [NSURLCredential credentialWithUser:userName password:self.password persistence:NSURLCredentialPersistenceForSession]; [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:[self.url host] port:0 protocol:self.url.scheme realm:[self.url host] authenticationMethod:authMethod]; [[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace]; } else { NSLog(@"Authentication error"); NSLog(@"Failed login with status code: %d", [(NSHTTPURLResponse*)[challenge failureResponse]statusCode]); [[challenge sender] cancelAuthenticationChallenge:challenge]; } } 

到目前为止我所遇到的两个全球性问题都是使用这种方法:

1)根据查尔斯嗅探器,到服务器的所有请求加倍(根据苹果文件,这是一个预期的行为)。 但是,与使用setValue:forHTTPHeader:直接设置标题相比,它会导致缺乏性能(两个请求而不是一个请求)。

2)不是每个请求都被调用。 例如,当我试图从服务器获取图像时,它将返回302(redirect到login网页)HTTP代码而不是401 HTTP代码,所以这根本不起作用。

我想完成的是抓取正确的授权头一次,然后把它手动放在每一个后来的NSMutableURLRequest我做。 我可以手动编写HTTP基本授权,这很简单,但我不能以相同的方式编写NTLM头,这就是为什么我依靠didReceiveAuthenticationChallenge:方法。

请你指出,我怎样才能收到由NSURLProtectionSpace自动设置的授权标题,所以每个请求最初都会被授权?

PS我试图接收它

 [connection.currentRequest allHTTPHeaderFields]; 

但它返回一个空的数组。 我为此奋斗了两天以上,任何帮助将不胜感激!