多线程与网络之cookies

1. 网络请求中的cookie

1.1 删除cooki

NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]; //删除cookie
for (NSHTTPCookie *tempCookie in cookies) {
[cookieStorage deleteCookie:tempCookie];
}

1.2 获取并保存cookie

/*
* 把cookie进行归档并转换为NSData类型
* 注意:cookie不能直接转换为NSData类型,否则会引起崩溃。
* 所以先进行归档处理,再转换为Data
*/
NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]]; //存储归档后的cookie
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject: cookiesData forKey: @"cookie"];

1.3 取出保存的cookie并设置

NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
if ([sharedHTTPCookieStorage cookieAcceptPolicy] != NSHTTPCookieAcceptPolicyAlways) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
} //取出保存的cookie
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; //对取出的cookie进行反归档处理
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:[userDefaults objectForKey:@"cookie"]]; if (cookies) {
NSLog(@"有cookie");
//设置cookie
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (id cookie in cookies) {
[cookieStorage setCookie:(NSHTTPCookie *)cookie];
}
}else{
NSLog(@"无cookie");
}
上一篇:CAS及其ABA问题


下一篇:Echarts - js