Set cookies in IOS network requests
1. ASIHTTPRequest
ASIHTTPRequest is an extremely powerful open source project for HTTP access. Let simple APIs complete complex functions, such as: asynchronous requests, queue requests, GZIP compression, caching, breakpoint relay, progress tracking, uploading files, and HTTP authentication.
Cookie support
If a cookie exists, the information will be shared in the NSHTTPCookieStorage container and will be used for next time. You can use [ ASIHTTPRequest setSessionCookies:nil ] ; to clear all cookies. Of course, you can also cancel the default cookie policy and make custom cookies:
-(NSMutableArray*)retrunCookies{ NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease]; [properties setValue:[LoginViewController getLanguageType:] forKey:NSHTTPCookieValue]; [properties setValue:@".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]]; //sendcookies,According to user's choice,Return to the corresponding language。
2. NSMutableURLRequest (can be used for webview)
NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease]; [properties setValue:userId forKey:NSHTTPCookieValue]; [properties setValue:@"" 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:] forKey:NSHTTPCookieValue]; [properties1 setValue:@".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];
Thank you for reading, I hope it can help you. Thank you for your support for this site!