IOS 网络请求中设置COOKIE
1. ASIHTTPRequest
ASIHTTPRequest 是一款极其强劲的 HTTP 访问开源项目。让简单的 API 完成复杂的功能,如:异步请求,队列请求,GZIP 压缩,缓存,断点续传,进度跟踪,上传文件,HTTP 认证。
COOKIE的支持
如果 COOKIE 存在的话,会把这些信息放在 NSHTTPCOOKIEStorage 容器中共享,并供下次使用。你可以用 [ ASIHTTPRequest setSessionCOOKIEs:nil ] ; 清空所有 COOKIEs。当然,你也可以取消默认的COOKIE策略,而使自定义的COOKIE:
-(NSMutableArray*)retrunCOOKIEs{ NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease]; [properties setValue:[LoginViewController getLanguageType:loginInfo.lang] forKey:NSHTTPCOOKIEValue]; [properties setValue:@"BENGGURU.GAIA.CULTURE_CODE" forKey:NSHTTPCOOKIEName]; [properties setValue:@"" forKey:NSHTTPCOOKIEDomain]; [properties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCOOKIEExpires]; [properties setValue:@"" forKey:NSHTTPCOOKIEPath]; NSHTTPCOOKIE *COOKIE = [[[NSHTTPCOOKIE alloc] initWithProperties:properties] autorelease]; return [NSMutableArray arrayWithObject:COOKIE]; }
[request setRequestCOOKIEs:[self retrunCOOKIEs]]; //发送COOKIEs,根据用户的选择,返回相应语言。
2. NSMutableURLRequest(可以用于webview)
NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease]; [properties setValue:userId forKey:NSHTTPCOOKIEValue]; [properties setValue:@"BENQGURU.GAIA.USERID" forKey:NSHTTPCOOKIEName]; [properties setValue:@"" forKey:NSHTTPCOOKIEDomain]; [properties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCOOKIEExpires]; [properties setValue:@"/" forKey:NSHTTPCOOKIEPath]; NSHTTPCOOKIE *COOKIE = [[[NSHTTPCOOKIE alloc] initWithProperties:properties] autorelease]; NSDictionary *properties1 = [[[NSMutableDictionary alloc] init] autorelease]; [properties1 setValue:[LoginViewController getLanguageType:loginInfo.lang] forKey:NSHTTPCOOKIEValue]; [properties1 setValue:@"BENGGURU.GAIA.CULTURE_CODE" forKey:NSHTTPCOOKIEName]; [properties1 setValue:@"" forKey:NSHTTPCOOKIEDomain]; [properties1 setValue:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCOOKIEExpires]; [properties1 setValue:@"/" forKey:NSHTTPCOOKIEPath]; NSHTTPCOOKIE *COOKIE1 = [[[NSHTTPCOOKIE alloc] initWithProperties:properties1] autorelease]; NSArray *COOKIEs=[NSArray arrayWithObjects:COOKIE,COOKIE1,nil]; NSDictionary *headers=[NSHTTPCOOKIE requestHeaderFieldsWithCOOKIEs:COOKIEs]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:[object valueForKey:@"url"]]]; [request setValue:[headers objectForKey:@"COOKIE"] forHTTPHeaderField:@"COOKIE"]; [webView loadRequest:request];
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!