I'm hoping someone can shed some light on the following, I think I am heading in the right direction with this. I want to login to my serv开发者_StackOverflow社区er with a user/pass combo, then I need to be able to tell If I logged in correctly (a cookie should be dropped), then I will make another request if this is the case.
Any help appreciated, heres the code I am working with:
[[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..
This should work:
NSDictionary *headerFields = [(NSHTTPURLResponse*)response allHeaderFields];
NSURL *url = [NSURL URLWithString:@"http://www.mywebserver.com/login.php"];
NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:headerFields forURL:url];
Then you can know if the cookies
array contains the cookie you want.
You could also call this after receiving the response:
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
Here is a possible solution using your current code:
1 - What you do at the beginning is good: setting the cookie policy generally.
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHttpCookieStorage];
[cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
2 - After that, in you requests, you need to specify that you want to use cookies (in order to inject the session information):
[request setHTTPShouldHandleCookies:YES];
You need to set this field for the authentication and the subsequent requests.
精彩评论