NSHTTPCookieStorage ios cookie

cookie机制采用的是在客户端保持 HTTP 状态信息的方案

Cookie是在浏览器访问WEB服务器的某个资源时,由WEB服务器在HTTP响应消息头中附带传送给浏览器的一个小文本文件。

一旦WEB浏览器保存了某个Cookie,那么它在以后每次访问该WEB服务器时,都会在HTTP请求头中将这个Cookie回传给WEB服务器。

底层的实现原理: WEB服务器通过在HTTP响应消息中增加Set-Cookie响应头字段将Cookie信息发送给浏览器,浏览器则通过在HTTP请求消息中增加Cookie请求头字段将Cookie回传给WEB服务器。

一个Cookie只能标识一种信息,它至少含有一个标识该信息的名称(NAME)和设置值(VALUE)。

一个WEB站点可以给一个WEB浏览器发送多个Cookie,一个WEB浏览器也可以存储多个WEB站点提供的Cookie。

浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4KB。

一、NSHTTPCookieStorage  【转自 http://rainbird.blog.51cto.com/211214/805173】

一 直以为iOS的http请求这块很简单应该不支持记录,保存,或者使用cookie,可是想当然归想当然,真用的时候,真研究了一下发现还真强大。经过一 番的研究简单说一下我的理解:当你访问一个网站时,不管你愿意或者不愿意,NSURLRequest都会帮你主动记录下来你访问的站点设置的 cookie,而且很负责任的,当你下次再访问这个站点时,NSURLRequest会拿着上次保存下来了的cookie继续去请求。这规律同样适用于 ASIHTTPRequest。所以当你做一些基于认证的网络请求时,cookie不失为一个完美的解决方案。

那么怎么查看cookie呢?很简单:

NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

for (NSHTTPCookie *cookie in [cookieJar cookies]) {

NSLog(@"%@", cookie);

}

这样就列出了所有已保存的cookie,如果当前为空怎么办呢?随便请求一个url喽。

NSURLRequest *request = [NSURLRequest requestWithURL:

[NSURL URLWithString:@"http://blog.cnrainbird.com"]

cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData    timeoutInterval:3];

[NSURLConnection sendSynchronousRequest:request

returningResponse:nil

error:nil];

NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

for (NSHTTPCookie *cookie in [cookieJar cookies]) {

NSLog(@"%@", cookie);

}

是不是得到了类似:

1

的东东?这就是cookie啦

怎么清空cookie呢?

NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];

NSArray *_tmpArray = [NSArray arrayWithArray:[cookieJar cookies]];

for (id obj in _tmpArray) {

[cookieJar deleteCookie:obj];

}

这样cookie就消失的一干二净了。

会查看cookie了,也会清空cookie了,怎么设置指定的cookie呢?

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];

[cookieProperties setObject:@"username" forKey:NSHTTPCookieName];

[cookieProperties setObject:@"rainbird" forKey:NSHTTPCookieValue];

[cookieProperties setObject:@"cnrainbird.com" forKey:NSHTTPCookieDomain];

[cookieProperties setObject:@"cnrainbird.com" forKey:NSHTTPCookieOriginURL];

[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];

[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

这样就可以了。输入一下,是不是得到了下面这样的结果:

1

二、

1.NSHttpCookiesStorage是一个单例,管理所有的Cookie,每个Cookie都是一个NSHTTPCookie的实例,所有应用的cookies都被保存在这个NSHTTPCookieStorage的单例中,并且跨进程同步。  但为了安全,每个应用都有自己的沙盒,A应用的cookie是不能被B应用访问的。

iOS Note: Cookies are not shared among applications in iOS.

2. cookie的接收模式有3种

NSHTTPCookieAcceptPolicyAlways,NSHTTPCookieAcceptPolicyNever,NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain

如果改变cookie的接收模式,会影响所有当前正在使用cookie storage正在运行的应用。

Note:Changes made to the cookie accept policy affect all currently running applications using the cookie storage.

3.Session cookies (where the cookie object’sisSessionOnlymethod returnsYES) are local to a single process and are not shared.

4.NSHTTPCookieStorage的问题,即当更改或者删除一个cookie时,NSHTTPCookieStorage不是立即接收NSHTTPCookieManagerCookiesChangedNotification,然后进行更改,而是有5s的延迟,

参考:http://stackoverflow.com/questions/5837702/nshttpcookiestorage-state-not-saved-on-app-exit-any-definitive-knowledge-docume

http://www.cocoabuilder.com/archive/cocoa/195413-nshttpcookiestorage-notification-troubles.html

一般解决方法是把cookie手动的保存,隔一段时间刷新,程序启动时再从NSDefaultUser中读出

NSHTTPCookieStorage state not saved on app exit. Any definitive knowledge/documentation out there?

I also got the same problem but i found a solution. I saved the cookies as it get created by the browser and then recreate them as app restarts.

1) Save cookie when they get created by uiwebview.

NSMutableArray *cookieArray = [[NSMutableArray alloc] init];

for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {

[cookieArray addObject:cookie.name];

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];

[cookieProperties setObject:cookie.name forKey:NSHTTPCookieName];

[cookieProperties setObject:cookie.value forKey:NSHTTPCookieValue];

[cookieProperties setObject:cookie.domain forKey:NSHTTPCookieDomain];

[cookieProperties setObject:cookie.path forKey:NSHTTPCookiePath];

[cookieProperties setObject:[NSNumber numberWithInt:cookie.version] forKey:NSHTTPCookieVersion];

[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

[[NSUserDefaults standardUserDefaults] setValue:cookieProperties forKey:cookie.name];

[[NSUserDefaults standardUserDefaults] synchronize];

}

[[NSUserDefaults standardUserDefaults] setValue:cookieArray forKey:@"cookieArray"];

[[NSUserDefaults standardUserDefaults] synchronize];

2) Now recreate them as app restarts:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

NSMutableArray* cookieDictionary = [[NSUserDefaults standardUserDefaults] valueForKey:@"cookieArray"];

NSLog(@"cookie dictionary found is %@",cookieDictionary);

for (int i=0; i < cookieDictionary.count; i++)

{

NSLog(@"cookie found is %@",[cookieDictionary objectAtIndex:i]);

NSMutableDictionary* cookieDictionary1 = [[NSUserDefaults standardUserDefaults] valueForKey:[cookieDictionary objectAtIndex:i]];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieDictionary1];

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

}

// other code

}

I also got the same problem but i found a solution. I saved the cookies as it get created by the browser and then recreate them as app restarts.

1) Save cookie when they get created by uiwebview.

NSMutableArray *cookieArray = [[NSMutableArray alloc] init];

for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {

[cookieArray addObject:cookie.name];

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];

[cookieProperties setObject:cookie.name forKey:NSHTTPCookieName];

[cookieProperties setObject:cookie.value forKey:NSHTTPCookieValue];

[cookieProperties setObject:cookie.domain forKey:NSHTTPCookieDomain];

[cookieProperties setObject:cookie.path forKey:NSHTTPCookiePath];

[cookieProperties setObject:[NSNumber numberWithInt:cookie.version] forKey:NSHTTPCookieVersion];

[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

[[NSUserDefaults standardUserDefaults] setValue:cookieProperties forKey:cookie.name];

[[NSUserDefaults standardUserDefaults] synchronize];

}

[[NSUserDefaults standardUserDefaults] setValue:cookieArray forKey:@"cookieArray"];

[[NSUserDefaults standardUserDefaults] synchronize];

2) Now recreate them as app restarts:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

NSMutableArray* cookieDictionary = [[NSUserDefaults standardUserDefaults] valueForKey:@"cookieArray"];

NSLog(@"cookie dictionary found is %@",cookieDictionary);

for (int i=0; i < cookieDictionary.count; i++)

{

NSLog(@"cookie found is %@",[cookieDictionary objectAtIndex:i]);

NSMutableDictionary* cookieDictionary1 = [[NSUserDefaults standardUserDefaults] valueForKey:[cookieDictionary objectAtIndex:i]];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieDictionary1];

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

}

// other code

}

I also got the same problem but i found a solution. I saved the cookies as it get created by the browser and then recreate them as app restarts.

1) Save cookie when they get created by uiwebview.

NSMutableArray *cookieArray = [[NSMutableArray alloc] init];

for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {

[cookieArray addObject:cookie.name];

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];

[cookieProperties setObject:cookie.name forKey:NSHTTPCookieName];

[cookieProperties setObject:cookie.value forKey:NSHTTPCookieValue];

[cookieProperties setObject:cookie.domain forKey:NSHTTPCookieDomain];

[cookieProperties setObject:cookie.path forKey:NSHTTPCookiePath];

[cookieProperties setObject:[NSNumber numberWithInt:cookie.version] forKey:NSHTTPCookieVersion];

[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

[[NSUserDefaults standardUserDefaults] setValue:cookieProperties forKey:cookie.name];

[[NSUserDefaults standardUserDefaults] synchronize];

}

[[NSUserDefaults standardUserDefaults] setValue:cookieArray forKey:@"cookieArray"];

[[NSUserDefaults standardUserDefaults] synchronize];

2) Now recreate them as app restarts:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

NSMutableArray* cookieDictionary = [[NSUserDefaults standardUserDefaults] valueForKey:@"cookieArray"];

NSLog(@"cookie dictionary found is %@",cookieDictionary);

for (int i=0; i < cookieDictionary.count; i++)

{

NSLog(@"cookie found is %@",[cookieDictionary objectAtIndex:i]);

NSMutableDictionary* cookieDictionary1 = [[NSUserDefaults standardUserDefaults] valueForKey:[cookieDictionary objectAtIndex:i]];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieDictionary1];

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

}

// other code

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,311评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,339评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,671评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,252评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,253评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,031评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,340评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,973评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,466评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,937评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,039评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,701评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,254评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,259评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,485评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,497评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,786评论 2 345

推荐阅读更多精彩内容