2011-09-30 18 views
1

如果我知道的認證需要我的服務器API,是更快/更好地使用HTTP標頭,而不是等待服務器返回401響應,然後對此作出迴應NSURLConnection的委託方法連接內直接強制認證:didReceiveAuthenticationChallenge :?使用NSURLConnection而不是使用委託方法強制認證更快/更好的方法?

+0

是的,這會更快。 – Thilo

+0

Thilo,你的回答是基於(我在這裏猜測)客戶端和服務器之間的通信較少嗎?你可能想添加你的-comment-作爲答案。 –

+0

是的,服務器往返次數會減少一次。但沒有代碼示例如何在iOS中做到這一點,我不覺得它不僅僅是評論;-) – Thilo

回答

4

的「簡單的方法」提供身份驗證憑據到服務器是使用NSURLConnection的委託方法

didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 

在那裏你可以提供類似於此

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

    if ([challenge previousFailureCount] == 0) { 

     NSURLCredential *newCredential; 
     newCredential = [NSURLCredential credentialWithUser:userName password:password persistence:NSURLCredentialPersistenceNone]; 
     [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge]; 
    } else { 
     [[challenge sender] cancelAuthenticationChallenge:challenge]; 
    } 
} 

會發生什麼憑據是你首先使用GET/POST請求調用服務器,如果服務器需要身份驗證,並且HTTTP頭中沒有提供證書,它將(希望)響應401響應。上述方法將觸發並提供提供的憑證。

但是,如果你知道你的服務器總是需要身份驗證,它是沒有效率,使這個額外的一輪客戶/服務器通信的,你會好起來的,以提供您的憑據HTTP報頭內立竿見影。

HTTP報頭內提供憑證的方法是簡單除了以下事實:iOS不附帶編碼爲BASE64的方法。

NSMutableURLRequest *aRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30]; 

// first create a plaintext string in the format username:password 
NSMutableString *loginString = (NSMutableString *)[@"" stringByAppendingFormat:@"%@:%@", userName, password]; 

// encode loginString to Base64 
// the Base64 class is not provided and you will have to write it! 
NSString *encodedLoginData = [Base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]]; 

// prepare the header value 
NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", encodedLoginData]; 

// add the authentication credential into the HTTP header 
[request addValue:authHeader forHTTPHeaderField:@"Authorization"]; 

// provide additional HTTP header properties (optional)  
[aRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
[aRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[aRequest setHTTPMethod:@"GET"]; 

// and finally create your connection for above request 
NSURLConnection *aConnection = [[NSURLConnection alloc] initWithRequest:aRequest delegate:self]; 

// don't forget to release the request and nsurlconnection when appropriate... 
+0

嗨@ peter-pajchl,感謝您的解釋。它爲我工作。但是我仍然遇到了下面這行代碼從服務器加載圖片的問題(我認爲這是由於相同的認證問題)。 [myImageView setImage:[UIImage的imageWithData:[NSData的dataWithContentsOfURL:[NSURL URLWithString:[DIC objectForKey:@ 「圖像」]]]]]; 能否請你幫我 –

+0

@SudhanshuSrivastava從代碼很難確定哪些可能是問題的片段。我建議你創建一個新問題,並提供更多信息以及你正在獲得的http響應。但是,你應該看看......在你的代碼中,我沒有看到你在準備「請求」和設置你的憑證。 –

相關問題