When you visit a website, Nsurlrequest will help you to take the initiative to record the cookies you visit, if the cookie exists, it will be shared in the Nshttpcookiestorage container, when you visit the site next time, Nsurlrequest will take the last saved cookie and continue to request it.
The same applies to asihttprequest,afnetworking, WebView, etc., cookies are often used for some authentication-based network requests
Meet the Nshttpcookiestorage
Nshttpcookiestorage implements a single instance of managing cookies (only one), each of which is an instance of the Nshttpcookie class, the most common one, in which cookies are shared across all applications and are kept synchronized between different processes. The Session cookie (a cookie that issessiononly method returns YES) can only be used in a single process.
Cookies
Cookies are generated by the server, sent to User-agent (typically a browser or client), the browser will save the cookie key/value to a text file in a directory, the next time you request the same website address, send the cookie to the server
HTTP Header
The HTTP header contains the action parameters for the HTTP request and response. The Header property defines the various characteristics of the transmitted data. The header property starts with the property name, ends with a colon, and finally the property value. Attribute names and values vary by application
I. IOS htttp network request cookie Read and write:
The cookie is bound to pass through the HTTP respone, and the cookie is in the HTTP header in Respone. No matter what the request framework, there will inevitably exist respone objects, such as afnetworking2.x operation.response,afnetworking3.x task.response and so on ....
1. Native Nsurlconnection notation
I. Get cookie-(ibaction) cookietouched: (ID) Sender {nsurl *url = [Nsurl urlwithstring:@] http://api.skyfox.org/ Api-test.php "]; Nsurlrequest *request = [Nsurlrequest Requestwithurl:url] Cachepolicy:nsurlreq Uestreloadignoringlocalandremotecachedata Timeoutinterval:3]; Nsoperationqueue *queue = [[Nsoperationqueue alloc] init]; [Nsurlconnection sendasynchronousrequest:request Queue:queue completionhandler:^ (Nsurlresponse *response, NSData *data, Nserror *error) {//convert NSURLRESP Onse becomes httpresponse nshttpurlresponse *httpresponse = (Nshttpurlresponse *) response; Get headerfields nsdictionary *fields = [HttpResponse allheaderfields ];//Native nsurlconnection notation//Nsdictionary *fields = [Operation.respOnse Allheaderfields]; Afnetworking notation NSLog (@ "fields =%@", [fields description]); Get Cookie Method 1//Nsarray *cookies = [Nshttpcookie cookieswithresponseheaderfields:fields fo Rurl:url]; Get Cookie Method 2//nsstring *cookiestring = [[HttpResponse allheaderfields] valueforkey:@ "set-c Ookie "]; Get Cookie Method 3 Nshttpcookiestorage *cookiejar = [Nshttpcookiestorage sharedhttpcookiestorage] ; For (Nshttpcookie *cookie in [Cookiejar cookies]) {NSLog (@ "cookie%@", cookies); } }];}
2.AFNetworking notation
[[Apiclient sharedclient] postpath:@ "http://api.skyfox.org/api-test.php" Parameters:p success:^ ( Afhttprequestoperation *operation, id JSON) { nsdictionary *fields = [Operation.response allheaderfields];// Afnetworking notation NSLog (@ "fields =%@", [fields description]); Nsurl *url = [Nsurl urlwithstring:@ "http://api.skyfox.org/api-test.php"]; Get Cookie Method 1 nsarray *cookies = [Nshttpcookie cookieswithresponseheaderfields:fields forurl:url]; Get Cookie Method 2 //nsstring *cookiestring = [[HttpResponse allheaderfields] valueforkey:@ "Set-cookie"]; } failure:^ (afhttprequestoperation *operation, Nserror *error) { }];
Two. Empty cookies
Nshttpcookiestorage *cookiejar = [Nshttpcookiestorage sharedhttpcookiestorage]; Nsarray *cookiearray = [Nsarray arraywitharray:[cookiejar cookies]]; for (id obj in cookiearray) { [Cookiejar deletecookie:obj]; }
Three. Manually set cookies manually set cookies are not automatically persisted to the sandbox
First request manually set cookie-(void) Test1: (nsstring*) urlstring{nsurl *url = [Nsurl urlwithstring:@] http://api.skyfox.org/ Cookie.php "]; Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url]; Nsmutabledictionary *cookieproperties = [Nsmutabledictionary dictionary]; [Cookieproperties setobject:@ "username" forkey:nshttpcookiename]; [Cookieproperties setobject:@ "My iOS cookie" forkey:nshttpcookievalue]; [Cookieproperties setobject:@ "api.skyfox.org" forkey:nshttpcookiedomain]; [Cookieproperties setobject:@ "api.skyfox.org" forkey:nshttpcookieoriginurl]; [Cookieproperties setobject:@ "/" forkey:nshttpcookiepath]; [Cookieproperties setobject:@ "0" forkey:nshttpcookieversion]; [Cookieproperties setobject:[nsdate datewithtimeintervalsincenow:60*60] forkey:nshttpcookieexpires];//set Expiration time [ Cookieproperties setobject:@ "0" forkey:nshttpcookiediscard]; Set sessiononly Nshttpcookie *cookie = [Nshttpcookie cookiewithproperties:cookieproperties]; [[NshttpcookIestorage Sharedhttpcookiestorage] Setcookie:cookie]; [Self.mywebview loadrequest:request];} The second request will automatically take cookie-(ibaction) Test2: (ID) Sender {nsurl *url = [Nsurl urlwithstring:@] http://api.skyfox.org/cookie.php "]; Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url]; [Self.mywebview2 loadrequest:request];}
Request can also set a cookie like this
[Request Sethttpshouldhandlecookies:yes]; [Request setvalue:[nsstring stringwithformat:@ "%@=%@", [cookie name], [cookie value]] forhttpheaderfield:@ "Cookie"];
Four. Local cache policy for cookies
Nshttpcookieacceptpolicyalways: Save All Cookies, this is the default value//nshttpcookieacceptpolicynever: Do not save any cookie//in the response header Nshttpcookieacceptpolicyonlyfrommaindocumentdomain: Save only the domain request matching cookie [[Nshttpcookiestorage sharedhttpcookiestorage ]setcookieacceptpolicy:nshttpcookieacceptpolicynever];
Five. Persistent storage of cookies 1. Server-side settings cookie, PHP for example syntax
1 |
Setcookie(name,value,expire,path,domain,secure) |
Parameters |
Description |
Name |
Necessary. Specifies the name of the cookie. |
Value |
Necessary. Specifies the value of the cookie. |
Expire |
Optional. Specify the validity period of the cookie. |
Path |
Optional. Specifies the server path of the cookie. |
Domain |
Optional. Specifies the domain name of the cookie. |
Secure |
Optional. Specifies whether to transfer cookies through a secure HTTPS connection. |
123 |
setcookie (," my cookie value ") //not set expiration time after closing the app the system will not persist cookies setcookie ( "TestCookie" , "My cookie value", time (+ 3600*24) //set expire expiration time after closing the app The system automatically persists cookies |
If the server set the cookie expiration time expiresdate, Sessiononly:false will be persisted to the file, kill the system automatically save after killing, The next time you start the app, it will automatically load. Cookies in Binarycookies, the following is a cookie output
1 |
<NshttpcookieVersion:0Name:"TestCookie"Value:"My+cookie+value"Expiresdate:2016-04-0809:31:09+0000Created:2016-04-08 09:30:49 +0000 Sessiononly:false domain : "api.skyfox.org" path:issecure:false> |
Persisted to the file, the address is the/library/cookies/org.skyfox.afnetworking-demo.binarycookies of the sandbox
Using the binarycookiereader.py script to parse the org.skyfox.afnetworking-demo.binarycookies result is as follows
2.app-Side Manual cookie Storage
If you do not set the cookie expiration time expiresdate: (null), the system does not automatically save the cookie after Sessiononly:true,kill is dropped, if you want to persist cookies to mimic the browser to save cookies, Save with Nsuserdefaults, here is a cookie output
1 |
<NshttpcookieVersion:0Name:"TestCookie"Value:"My+cookie+value"Expiresdate:(Null)Created:2016-Geneva-Geneva:: +0000 sessiononly: TRUE domain:"api.skyfox.org" path:"/" issecure: FALSE> |
Save manually
The right time to save cookie-(void) savecookies{ nsdata *cookiesdata = [Nskeyedarchiver archiveddatawithrootobject: [[ Nshttpcookiestorage sharedhttpcookiestorage] [cookies]]; Nsuserdefaults *defaults = [Nsuserdefaults standarduserdefaults]; [Defaults setobject:cookiesdata Forkey: @ "Org.skyfox.cookie"]; [Defaults synchronize];} The right time to load a cookie is typically when the app just starts-(void) loadcookies{ nsarray *cookies = [Nskeyedunarchiver unarchiveobjectwithdata : [[Nsuserdefaults Standarduserdefaults] Objectforkey: @ "Org.skyfox.cookie"]; Nshttpcookiestorage *cookiestorage = [Nshttpcookiestorage sharedhttpcookiestorage]; For (Nshttpcookie *cookie in cookies) { [cookiestorage Setcookie:cookie];} }
IOS htttp Network Request cookie Read and write (nshttpcookiestorage)