IOS HTTP Network Request cookie Read and write (nshttpcookiestorage)

Source: Internet
Author: User
Tags setcookie

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. Obtaining a cookie

-(Ibaction) cookietouched: (ID) Sender {
Nsurl *url = [Nsurl urlwithstring:@ "http://api.skyfox.org/api-test.php"];
Nsurlrequest *request = [Nsurlrequest Requestwithurl:url]
Cachepolicy:nsurlrequestreloadignoringlocalandremotecachedata
Timeoutinterval:3];
Nsoperationqueue *queue = [[Nsoperationqueue alloc]init];
[Nsurlconnection Sendasynchronousrequest:request
Queue:queue
completionhandler:^ (Nsurlresponse *response, NSData *data, Nserror *error) {

Convert Nsurlresponse into 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 forurl:url];
Get Cookie Method 2
NSString *cookiestring = [[HttpResponse allheaderfields] valueforkey:@ "Set-cookie"];
Get Cookie Method 3
Nshttpcookiestorage *cookiejar = [Nshttpcookiestorage sharedhttpcookiestorage];
For (Nshttpcookie *cookie in [Cookiejar cookies]) {
NSLog (@ "cookie%@", cookie);
}
}];
}


2.AFNetworking notation

Afhttpsessionmanager *manager = [Afhttpsessionmanager manager];
Manager.responseserializer = [Afcompoundresponseserializer serializer];
The API in the demo returns the HTML data, not the JSON
[Manager post:@ "http://dev.skyfox.org/cookie.php" Parameters:nil progress:^ (nsprogress * _nonnull uploadprogress) {

} success:^ (Nsurlsessiondatatask * _nonnull task, id _nullable responseobject) {
NSLog (@ "\n======================================\n");
Nsdictionary *fields = ((nshttpurlresponse*) task.response). Allheaderfields;
NSLog (@ ' fields =%@ ', [fields description]);
Nsurl *url = [Nsurl urlwithstring:@ "http://dev.skyfox.org/cookie.php"];
NSLog (@ "\n======================================\n");
Get Cookie Method 1
Nsarray *cookies = [Nshttpcookie cookieswithresponseheaderfields:fields forurl:url];
For (Nshttpcookie *cookie in cookies) {
NSLog (@ "cookie,name:=%@,valuie =%@", cookie.name,cookie.value);
}
NSLog (@ "\n======================================\n");
Get Cookie Method 2
NSString *cookies2 = [((nshttpurlresponse*) task.response) valueforkey:@ "Set-cookie"];
NSLog (@ "cookies2 =%@", [cookies2 description]);

} failure:^ (Nsurlsessiondatatask * _nullable task, Nserror * _nonnull error) {

}];

Two. Empty cookies

Nshttpcookiestorage *cookiejar = [Nshttpcookiestorage sharedhttpcookiestorage];
Nsarray *cookiearray = [Nsarray arraywitharray:[cookiejar cookies]];
For (Nshttpcookie *obj in Cookiearray) {
[Cookiejar Deletecookie:obj];
}

Three. Manually set cookies manually set cookies are not automatically persisted to the sandbox

First request to set a cookie manually
-(void) Test1: (nsstring*) urlstring{
Nsurl *url = [Nsurl urlwithstring:@ "http://dev.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:@ "dev.skyfox.org" forkey:nshttpcookiedomain];
[Cookieproperties setobject:@ "dev.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 bring a cookie
-(Ibaction) Test2: (ID) Sender {
Nsurl *url = [Nsurl urlwithstring:@ "http://dev.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 cookies 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.

Setcookie ("TestCookie", "My Cookie Value"); The system does not persist cookies after you close the app without setting the expiration time

Setcookie ("TestCookie", "My Cookie Value", Time () +3600*24); Set expire expiration time the system automatically persists cookies after closing the app


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

<nshttpcookie version:0 Name: "TestCookie" Value: "My+cookie+value" expiresdate:2016-04-08 09:31:09 +0000 created : 2016-04-08 09:30:49 +0000 sessiononly:false domain: "dev.skyfox.org" Path: "/" issecure:false>

Persisted to the file, the address is the/library/cookies/org.skyfox.ios-cookie.binarycookies of the sandbox

Using the terminal to perform binarycookiereader.py script parsing org.skyfox.ios-cookie.binarycookies results are as follows:

Jakey-mini:cookies jakey$ python binarycookiereader.py org.skyfox.ios-cookie.binarycookies
#*************************************************************************#
# binarycookiereader:developed by Satishb3:http://www.securitylearn.net #
#*************************************************************************#
Cookie:testphpwritecookie=php+write+my+cookie+value; domain=dev.skyfox.org; path=/; Expires=thu, DEC 2016;

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

<nshttpcookie version:0 Name: "TestCookie" Value: "My+cookie+value" expiresdate: (NULL) created:2016-04-08 09:33:34 + 0000 sessiononly:true domain: "dev.skyfox.org" Path: "/" issecure:false>

Save manually

The right time to persist cookies
-(void) savecookies{
NSData *cookiesdata = [Nskeyedarchiver archiveddatawithrootobject: [[Nshttpcookiestorage SharedHTTPCookieStorage] Cookies]];
Nsuserdefaults *defaults = [Nsuserdefaults standarduserdefaults];
[Defaults setobject:cookiesdata forkey:@ "Org.skyfox.cookiesave"];
[Defaults synchronize];
}
The right time to load persistent cookies are generally when the app just starts
-(void) loadsavedcookies{
Nsarray *cookies = [Nskeyedunarchiver unarchiveobjectwithdata: [[Nsuserdefaults Standarduserdefaults] ObjectForKey: @ " Org.skyfox.cookiesave "];
Nshttpcookiestorage *cookiestorage = [Nshttpcookiestorage sharedhttpcookiestorage];
For (Nshttpcookie *cookie in cookies) {
NSLog (@ "cookie,name:=%@,valuie =%@", cookie.name,cookie.value);
}
}

Demo Address

IOS HTTP Network Request cookie Read and write (nshttpcookiestorage)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.