如何为NSHTTPURLResponse获取正确的Set-Cookie标头?

时间:2010-03-23 14:10:31

标签: cocoa macos nsurlconnection setcookie

我想使用以下代码登录到以下列方式返回其cookie信息的网站:

Set-Cookie: 19231234
Set-Cookie: u2am1342340
Set-Cookie: owwjera

我正在使用以下代码登录该站点,但最后的print语句不会输出任何有关“set-cookie”的内容。 在Snow leopard上,库似乎会自动为此站点获取cookie,之后发送的连接将使用正确的“cookie”标头设置。但是在leopard上,它不会那样工作,所以触发这个“记住某个根URL的cookie”行为吗?

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:uurl]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"keep-live" forHTTPHeaderField:@"Connection"];
[request setValue:@"300" forHTTPHeaderField:@"Keep-Alive"];
[request setHTTPShouldHandleCookies:YES];

[request setHTTPBody:postData];
[request setTimeoutInterval:10.0];

NSData *urlData;
NSHTTPURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:request
                                returningResponse:&response
                                            error:&error];

NSLog(@"response dictionary %@",[response allHeaderFields]);

1 个答案:

答案 0 :(得分:6)

[request setHTTPShouldHandleCookies:YES];

此行会导致系统为您处理Cookie。