【发布时间】:2014-11-15 17:47:48
【问题描述】:
我已经解决这个问题好几天了。我的应用需要登录到 ASP.NET(版本:4.0.30319,MVC 版本:3.0)服务器,然后通过 NSMutableURLRequest 发布到受限页面(需要您登录才能访问的页面)。
目前我可以成功登录该网站。要登录,我使用此代码:
NSString *post =[[NSString alloc] initWithFormat:@"LogInEmail=%@&Password=%@",@"username@website.com",@"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 cookie 都可以在 sharedHTTPCookieStorage 中找到。我知道如果我想“登录”,这两个都需要随请求一起发送。
检查cookies的代码在这里:
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 值。
我觉得这真的很简单,有帮助吗?
【问题讨论】:
标签: ios asp.net cookies nsmutableurlrequest .aspxauth