关于iOS AFNetworking中Cookie的存取
@property (strong,nonatomic) AFHTTPSessionManager *manager;
@property (strong,nonatomic) NSMutableString *cookieValue;
@property (strong,nonatomic) NSMutableDictionary *cookieDic;
- (void)setupDownload{
self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[self.manager POST:@"http://117.131.215.74:11010/wp-login.php" parameters:@{@"log":_nameTF.text,@"pwd":_pawTF.text} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
_cookieDic = [NSMutableDictionary dictionary];
_cookieValue = [NSMutableString stringWithFormat:@"fromapp=ios;"];
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [cookieJar cookies]) {
[_cookieDic setObject:cookie.value forKey:cookie.name];
NSLog(@"====%@",cookie.value);
}
[[NSUserDefaults standardUserDefaults]setObject:_cookieDic forKey:Cookie];
[[NSUserDefaults standardUserDefaults]synchronize];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"----%@",error);
}];
}
- 当再次发起请求时需要将获取的cookie添加到请求头的方法
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
NSDictionary *dic = [userDefault dictionaryForKey:Cookie];
[userDefault synchronize];
for (NSString *key in dic) {
NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [dic valueForKey:key]];
NSLog(@"cookie -- %@",appendString);
[_cookieValue appendString:appendString];
}
[self.manager.requestSerializer setValue:_cookieValue forHTTPHeaderField:@"Cookie"];
[self.manager GET:@"要请求的地址" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"++++%@",error.description);
}];