iOS AFNetworking中cookie的读取与设置

时间:2021-01-18 19:11:00

参考: http://blog.csdn.net/zhaoxy_thu/article/details/20532879

实际上AFNetworking中并没有专门针对cookie封装的代码,但是由于它底层使用的是NSURLRequest,所以可以通过NSHTTPCookieStorage来操作cookie.

读取及保存cookie:

NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:[BESTHttpClient sharedClient].url_login]];

// NSDictionary *requestFields = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies]; // 这个方法可以获取包含Cookie 及 sessionid 的字典
NSData *cookieData = [NSKeyedArchiver archivedDataWithRootObject:cookies];
[[NSUserDefaults standardUserDefaults] setObject:cookieData forKey:BEST_LOGIN_COOKIE];

log:(cookie的日志样式)

cookies -- (
            <NSHTTPCookie version:0 name:"csrftoken" value:"AX5Xde7MbbOCDPJsCmhYl8RmPK3M4YMB" expiresDate:2017-08-10 05:16:54 +0000 created:2016-08-11 05:16:54 +0000 sessionOnly:FALSE domain:"192.168.1.47" path:"/" isSecure:FALSE>,
            <NSHTTPCookie version:0 name:"sessionid" value:"m675fhggawh3w18vmmujjwb67kyr9ook" expiresDate:2016-09-10 05:16:54 +0000 created:2016-08-11 05:16:54 +0000 sessionOnly:FALSE domain:"192.168.1.47" path:"/" isSecure:FALSE>,
            )

删除cookie:

NSData *cookieData = [[NSUserDefaults standardUserDefaults] objectForKey:BEST_LOGIN_COOKIE];
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookieData];
NSLog(@"cookies - %@", cookies);
for (NSHTTPCookie *cookie in cookies) {
   [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}

设置cookie:

NSData *cookieData = [[NSUserDefaults standardUserDefaults] objectForKey:BEST_LOGIN_COOKIE];
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookieData];
for (NSHTTPCookie *cookie in cookies) {
   [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}

注:

1. 通过以上方法保存cookie,即可实现在退出程序,下一次进入的时候不用登录而再次使用cookie

2. 通过以上方法设置的cookie,通过webview的loadRequest方法load NSURLRequest时可以共用cookie。