iOS開發(fā)ASIHTTPRequest中Cookie的使用
本文為大家介紹了iOS開發(fā)ASIHTTPRequest中Cookie的使用的內(nèi)容,其中包括持久化cookie,自己處理cookie等等內(nèi)容,希望對大家有所幫助。
持久化cookie
ASIHTTPRequest允許你使用全局存儲來和所有使用CFNetwork或者NSURLRequest接口的程序共享cookie。
如果設(shè)置useCookiePersistence為YES(默認(rèn)值),cookie會被存儲在共享的 NSHTTPCookieStorage 容器中,并且會自動被其他request重用。值得一提的是,ASIHTTPRequest會向服務(wù)器發(fā)送其他程序創(chuàng)建的cookie(如果這些cookie對特定request有效的話)。
你可以清空session期間創(chuàng)建的所有cookie:
- [ASIHTTPRequest setSessionCookies:nil];
這里的‘session cookies’指的是一個(gè)session中創(chuàng)建的所有cookie,而非沒有過期時(shí)間的cookie(即通常所指的會話cookie,這種cookie會在程序結(jié)束時(shí)被清除)。
另外,有個(gè)方便的函數(shù) clearSession可以清除session期間產(chǎn)生的所有的cookie和緩存的授權(quán)數(shù)據(jù)。
自己處理cookie
如果你愿意,你大可以關(guān)閉useCookiePersistence,自己來管理某個(gè)request的一系列cookie:
- //創(chuàng)建一個(gè)cookie
- NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease];
- [properties setValue:[@"Test Value" encodedCookieValue] forKey:NSHTTPCookieValue];
- [properties setValue:@"ASIHTTPRequestTestCookie" forKey:NSHTTPCookieName];
- [properties setValue:@".dreamingwish.com" forKey:NSHTTPCookieDomain];
- [properties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCookieExpires];
- [properties setValue:@"/asi-http-request/tests" forKey:NSHTTPCookiePath];
- NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:properties] autorelease];
- //這個(gè)url會返回名為'ASIHTTPRequestTestCookie'的cookie的值
- url = [NSURL URLWithString:@"http://www.dreamingwish.com/"];
- request = [ASIHTTPRequest requestWithURL:url];
- [request setUseCookiePersistence:NO];
- [request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];
- [request startSynchronous];
- //將會打印: I have 'Test Value' as the value of 'ASIHTTPRequestTestCookie'
- NSLog(@"%@",[request responseString]);