本文為大家介紹了iOS開發ASIHTTPRequest中Cookie的使用的內容,其中包括持久化cookie,自己處理cookie等等內容,希望對大家有所協助。
持久化cookie
ASIHTTPRequest允許你使用全域儲存來和所有使用CFNetwork或者NSURLRequest介面的程式共用cookie。
如果設定useCookiePersistence為YES預設值),cookie會被儲存在共用的 NSHTTPCookieStorage 容器中,並且會自動被其他request重用。值得一提的是,ASIHTTPRequest會向伺服器發送其他程式建立的cookie如果這些cookie對特定request有效話)。
你可以清空session期間建立的所有cookie:
- [ASIHTTPRequest setSessionCookies:nil];
這裡的‘session cookies’指的是一個session中建立的所有cookie,而非沒有到期時間的cookie即通常所指的會話cookie,這種cookie會在程式結束時被清除)。
另外,有個方便的函數 clearSession可以清除session期間產生的所有的cookie和緩衝的授權資料。
自己處理cookie
如果你願意,你大可以關閉useCookiePersistence,自己來管理某個request的一系列cookie:
- //建立一個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];
-
- //這個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]);