這里拿我之前的一個項目作為例子.
項目需求:1.用cookie做自動登錄;
? ? ? ? ? ? ? ? 2.所有的請求都必須帶上登錄拿到的cookie,作為身份識別.
這里我使用的是AFN請求.
廢話不多說,直接上代碼.
//獲取cookie
NSArray*allCookies = [[NSHTTPCookieStoragesharedHTTPCookieStorage]cookies];
[[NSUserDefaultsstandardUserDefaults]setObject:[allCookiescomponentsJoinedByString:@","]forKey:COOKIE];
for(NSHTTPCookie*tempCookieinallCookies)
{
//打印cookies
if([tempCookie.nameisEqualToString:@"JSESSIONID"]) {
NSDictionary*Request = [NSHTTPCookierequestHeaderFieldsWithCookies:allCookies];
[usersetObject:[RequestobjectForKey:@"Cookie"]forKey:@"mUserDefaultsCookie"];
[usersynchronize];
break;
}
}
登錄成功后,將cookie存儲到緩存中.
下面是將cookie塞到請求頭中,做請求
AFN:
AFHTTPSessionManager*manager = [AFHTTPSessionManagermanager];
manager.requestSerializer= [AFHTTPRequestSerializerserializer];
manager.responseSerializer= [AFJSONResponseSerializerserializer];
[manager.requestSerializersetValue:[[NSUserDefaultsstandardUserDefaults]objectForKey:@"mUserDefaultsCookie"]forHTTPHeaderField:@"Cookie"];
上面就是cookie的基礎使用了.
對了,這里要提一下.AFN做請求的時候是會自動攜帶之前請求URL的cookie的.
所以切換賬戶的時候,需要刪除之前的cookie.否則可能導致登錄失敗.
所以退出登錄最好remove下
[[NSURLCachesharedURLCache]removeCachedResponseForRequest:[NSURLRequestrequestWithURL:[NSURLURLWithString:[NSStringstringWithFormat:@"%@/login",HTTP_SERVER_ADDRESS]]]];