Managing HTTP Cookies on iPhone

倾然丶 夕夏残阳落幕 提交于 2019-11-26 23:44:37
Steve Madsen

NSURLConnection gives you cookie management for free. From the URL Loading System Programming Guide:

The URL loading system automatically sends any stored cookies appropriate for an NSURLRequest. unless the request specifies not to send cookies. Likewise, cookies returned in an NSURLResponse are accepted in accordance with the current cookie acceptance policy.

zonble

You can use the NSURLConnection class to perform a HTTP request to login the website, and retrieve the cookie. To perform a request, just create an instance of NSURLConnection and assign a delegate object to it.

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];

Then, implement a delegate method.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
    NSDictionary *fields = [HTTPResponse allHeaderFields];
    NSString *cookie = [fields valueForKey:@"Set-Cookie"]; // It is your cookie
}

Retain or copy the cookie string. When you want to perform another request, add it to your HTTP header of your NSURLRequest instance.

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]];
[request addValue:cookie forHTTPHeaderField:@"Cookie"];
Ranger Way

@zonble's answer only works in my localhost; If the server is not running locally, the "Set-Cookie" header is missing from the NSDictionary *fields = [HTTPResponse allHeaderFields];

Finally I found @benzado's solution works fine. Also see: iphone nsurlconnection read cookies @Tal Bereznitskey's answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!