我一直在這個問題幾天。我的應用程序需要登錄到ASP.NET(版本:4.0.30319,MVC版本:3.0)服務器,然後通過NSMutableURLRequest發佈到受限頁面(需要登錄才能訪問的頁面)。如何使用NSMutableURLRequest正確包含.ASPXAUTH和ASP.NET_SessionId cookie
目前我可以成功登錄到網站。登錄我用這個代碼:
NSString *post =[[NSString alloc] initWithFormat:@"LogInEmail=%@&Password=%@",@"[email protected]",@"password"];
NSURL *url=[NSURL URLWithString:@"http://www.website.com/LogIn"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *responseMeta = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseMeta error:&error];
我可以檢查並看到,無論是一個ASP.NET_SessionId和.ASPXAUTH餅乾,針對該網站,可以在sharedHTTPCookieStorage找到。我明白,如果我想「登錄」,這兩個都需要發送請求。
檢查餅乾的代碼是在這裏:
NSArray *cookiesForURL = [cookieJar cookiesForURL: [NSURL URLWithString: @"http://www.example.com"]];
for (cookie in cookiesForURL)
{
if([cookie.name compare:@"ASP.NET_SessionId"] == NSOrderedSame)
{
ASPdotNET_SessionId = [cookie value];
NSLog(@"ASP.NET_SessionId: %@" , ASPdotNET_SessionId);
}
if([cookie.name compare:@".ASPXAUTH"] == NSOrderedSame)
{
dotASPXAUTH = [cookie value];
NSLog(@".ASPXAUTH: %@" , dotASPXAUTH);
}
}
要清除的cookie使用:
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *each in [[cookieStorage cookiesForURL:[NSURL URLWithString:@"http://www.example.com"]] copy]) {
[cookieStorage deleteCookie:each];
}
我試圖張貼到受限制的網頁通過修改NSString *post
和NSUrl *url
並使用相同上面的代碼。
NSString *post =[[NSString alloc] initWithFormat:[MessageId stringByAppendingString:@"=%@"],Comment];
NSURL *url=[NSURL URLWithString:@"https://www.website.com/message
這是不成功的。我假設,因爲我以某種方式忽略了餅乾。我已經在這個代碼嘗試添加略低於[request setHTTPMethod:@"POST"];
:
[request addValue:ASPdotNET_SessionId forHTTPHeaderField:@"Cookie"];
和/或:
[request addValue:dotASPXAUTH forHTTPHeaderField:@"Cookie"];
其中ASPdotNET_SessionId
和dotASPXAUTH
是從sharedHTTPCookieStorage檢索的Cookie值。
我覺得這很簡單,有什麼幫助嗎?