我希望有人能够阐明以下内容,我认为我正在朝着正确的方向前进。我想使用用户/密码组合登录我的服务器,然后我需要能够判断我是否正确登录(应该删除 cookie),如果是这种情况,我将发出另一个请求。
感谢任何帮助,这是我正在使用的代码:
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
NSString *post =[NSString stringWithFormat:@"name=%@&pass=%@",@"foo", @"bar"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.mywebserver.com/login.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(data);
// HOW to Check if there was a Cookie dropped??
// Make another request..
这应该有效:
NSDictionary *headerFields = [(NSHTTPURLResponse*)response allHeaderFields];
NSURL *url = [NSURL URLWithString:@"http://www.mywebserver.com/login.php"];
NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:headerFields forURL:url];
然后你就可以知道是否cookies
数组包含你想要的cookie。
您也可以在收到响应后调用此方法:
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)