AFNetworking的请求头的cookie的值的获取和使用

时间:2022-11-13 21:55:22

       //其中  response为服务器返回数据

        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;

        NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStoragesharedHTTPCookieStorage];

      //cookie中可能有多组数据,找到你需要的那一组,并且保存到沙盒中

        for(NSHTTPCookie *cookiein [cookieJar cookies])

        {

            

            if ([cookie.nameisEqualToString:@"你需要的cookie的name"]) {

                NSUserDefaults *defaults = [NSUserDefaultsstandardUserDefaults];

                [defaults setObject:cookie.nameforKey:@"cookie.name"];

                [defaults setObject:cookie.valueforKey:@"cookie.value"];

                [defaults synchronize];

            }

            

        }

//cookie在AFNetworking的使用

        AFHTTPSessionManager *manager=[AFHTTPSessionManagermanager];

        manager.requestSerializer=[AFJSONRequestSerializerserializer];

        manager.responseSerializer=[AFHTTPResponseSerializerserializer];


        [manager.requestSerializersetHTTPShouldHandleCookies:YES];

        [manager.requestSerializersetValue:[NSStringstringWithFormat:@"%@=%@", cookiename, cookievalue]forHTTPHeaderField:@"Cookie"]; 


        [manager POST:@"" parameters:dictionaryprogress:^(NSProgress *_Nonnull uploadProgress) {

            NSLog(@"upload==%@",uploadProgress);

        } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {

         

        } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {

            NSLog(@"error==%@",error);

        }];