2010-09-08 94 views
1

所以我想用一個NSMutableURLRequest登錄我的網站,它通過一個帖子提供憑證。作爲一個noobie,我對這個方法的功能有一些疑問,以確保我能理解它。NSMutableURLRequest正確發佈

NSString *post = [NSString stringWithFormat:@"username=%@&password=%@&TARGET=%@",LoginId,LoginPwd,target]; 
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 
[request setHTTPShouldHandleCookies:YES]; 
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://somelogin.mycomp.verify.fcc"]]]; 
//[request setURL:url]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"]; 
[request setHTTPBody:postData]; 

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 

現在,這將通過委託方法自動處理任何重定向正確?它還會一路收集任何餅乾?另外,我應該使用異步請求嗎?謝謝!

更新: 所以我推斷一些cookie被請求和隨後的重定向忽略。有誰知道爲什麼會發生這種情況?

回答

0

你可以在同步登錄時做類似的事情......代碼並不完美,但這是一般的想法。

看看這裏的文檔

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/AuthenticationChallenges.html#//apple_ref/doc/uid/TP40009507-SW1

// credentials set here 
NSURLCredential *creds = [NSURLCredential credentialWithUser:LoginId password:LoginPwd 
              persistence:NSURLCredentialPersistenceForSession]; 

NSURLProtectionSpace *protectionedSpace = [[NSURLProtectionSpace alloc] 
    initWithHost:@"mycomp.verify.fcc" 
    port:8443 
    protocol:@"https" 
    realm:nil 
    authenticationMethod:nil]; 


[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:creds 
              forProtectionSpace:protectionedSpace]; 

// removed credentials from line... 
NSString *post = [NSString stringWithFormat:@"TARGET=%@",target]; 

這裏是做它異步

http://iosdevelopertips.com/networking/handling-url-authentication-challenges-accessing-password-protected-servers.html

+0

Intresting的教程,是有可能更改cookie存儲(安全)策略?我覺得,因爲它在不同的域上進行身份驗證,隨後的重定向不會收集cookie。 – gabaum10 2010-09-08 17:48:25

+0

我已經實施了一個解決方案,在該解決方案中,我加載了憑證存儲中特定域的所有憑據...因此,如果URL需要憑據,他們可以從商店 – 2010-09-08 17:54:30

+0

中檢索它們,但我沒有選擇使用基於挑戰的認證。我必須通過所有的箍來收集餅乾。如果我有這個選項,這將會更容易... – gabaum10 2010-09-08 18:31:58