我希望有人能够阐明以下内容,我认为我正在朝着正确的方向前进。我想使用用户/密码组合登录我的服务器,然后我需要能够判断我是否正确登录(应该删除 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];
关于iPhone发出POST请求,处理cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1660927/