Asihttprequest加Cookie

持久化Cookie

ASIHTTPRequest允许你使用全局存储来和所有使用CFNetwork或者NSURLRequest接口的程序共享cookie。

如果设置useCookiePersistence为YES(默认值),cookie会被存储在共享的 NSHTTPCookieStorage 容器中,并且会自动被其他request重用。值得一提的是,ASIHTTPRequest会向服务器发送其他程序创建的cookie(如果这些cookie对特定request有效的话)。

你可以清空session期间创建的所有cookie:

[ASIHTTPRequest setSessionCookies:nil];

这里的‘session cookies’指的是一个session中创建的所有cookie,而非没有过期时间的cookie(即通常所指的会话cookie,这种cookie会在程序结束时被清除)。

另外,有个方便的函数 clearSession可以清除session期间产生的所有的cookie和缓存的授权数据。

 

自己处理Cookie

如果你愿意,你大可以关闭useCookiePersistence,自己来管理某个request的一系列cookie:

//创建一个cookie 
NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease]; 
[properties setValue:[@"Test Value" encodedCookieValue] forKey:NSHTTPCookieValue]; 
[properties setValue:@"ASIHTTPRequestTestCookie" forKey:NSHTTPCookieName]; 
[properties setValue:@".dreamingwish.com" forKey:NSHTTPCookieDomain]; 
[properties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCookieExpires]; 
[properties setValue:@"/asi-http-request/tests" forKey:NSHTTPCookiePath]; 
NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:properties] autorelease]; 
    
//这个url会返回名为'ASIHTTPRequestTestCookie'的cookie的值 
url = [NSURL URLWithString:@"http://www.dreamingwish.com/"]; 
request = [ASIHTTPRequest requestWithURL:url]; 
[request setUseCookiePersistence:NO]; 
[request setRequestCookies:[NSMutableArray arrayWithObject:cookie]]; 
[request startSynchronous]; 
    
//将会打印: I have 'Test Value' as the value of 'ASIHTTPRequestTestCookie' 
NSLog(@"%@",[request responseString]);

 

参考:http://www.dreamingwish.com/dream-category/api-in-chinese/asihttprequest-doc

NSString *cookieString = [NSString stringWithString:[headers objectForKey:@"Cookie"]];
        
        NSMutableDictionary *cookieProperties = [[NSMutableDictionary alloc] init];
        [cookieProperties setValue:cookieString forKey:NSHTTPCookieValue];
        [cookieProperties setValue:@"QQCookie" forKey:NSHTTPCookieName];
        [cookieProperties setValue:@".QQ.com" forKey:NSHTTPCookieDomain];
        [cookieProperties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCookieExpires];
        [cookieProperties setValue:@"/" forKey:NSHTTPCookiePath];
        NSHTTPCookie *newcookie = [[NSHTTPCookie alloc] initWithProperties:cookieProperties];
        
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:newcookie];

转载于:https://www.cnblogs.com/sany007/archive/2013/03/05/2944977.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值