Level: ★☆☆ tags: “iOS” “AFN Cookie” “NSURLSession Cookie” author: WYW


Preface The author recently read part of the content about cookies, wrote the following text, to share with you.

What is a Cookie

  • Cookie

Cookies, sometimes used in the plural, refer to data stored (usually encrypted) on a user’s local terminal by some web sites for identification and session tracking. 360 an cookies

This Session

  • Session

As HTTP is a stateless protocol, when the server needs to record the user status, it needs to use some mechanism to identify the specific user, and this mechanism is Session.

What does a Cookie do

The author introduces the use of cookies by taking simplified Chinese or simplified Chinese as an example:

(1) When we use the browser to visit Jianshu.com, the simple book server does not know the information of the browser. By default, the content displayed by the browser is simplified;

(2) When we set the browser display content to “traditional”, the browser will display traditional content;

(3) When we close the browser and reopen the browser, we find that the content displayed in the simple book will still be traditional; The author thinks that the reason is that the simple book server may make a unique record for the browser and store it in its own Session. After the browser restarts, it requests the simple book content from the server and sends the traditional content when the browser needs to display traditional content.

(4) If cookies are not used, because HTTP protocol is stateless, the display content set to traditional or simplified will not exist when we open a new page or close the browser and open it again.

The type of Cookie

From the definitive guide to HTTP

Broadly speaking, cookies fall into two categories: session cookies and persistent cookies

A session Cookie is a temporary Cookie that records a user’s Settings and preferences for accessing a long point. The session Cookie is deleted when the user exits the browser.

Persistent cookies last longer, they’re stored on hard drive, the browser exits, the computer restarts, they’re still there. Persistent cookies are typically used to maintain a profile or login name for a site that a user will visit periodically.

The only difference between session cookies and persistent cookies is their expiration time. A session Cookie is default when Expires is not specified.

Take a look at session cookies and persistent cookies for simple books:

The image above shows the cookies of Jianshu.com

Persistent cookies:

  • Expires Tue, 9 April 2018,09 Apr 2019 13:31:57-0000
    • My guess is that this value represents the current time minus 0000 to serve as a persistent Cookie
  • Domain for jianshu.com
  • The Path to /
  • Secure to YES
  • Http only is true;

A session Cookie:

  • Local: zh-cn is displayed as simplified.

Including session Cookie, the author thinks that session Cookie will disappear after closing the browser, but the author’s following test results are not sure whether it is a manifestation of the disappearance of session Cookie. The session Cookie displayed when the browser is started for the first time is:

local:zh-CN;

path:/;

default_font:font1;

Setting the situation of over-traditional:

local:zh-TW;

path:/;

default_font:font1;

And then refresh jianshu.com to show the content, and it just shows

local:zh-CN

or

local:zh-TW

I’m not sure if this counts as a session Cookie but when you close the browser, it disappears. Readers can also test it out for themselves. If the students who do the service end know, please inform.

Cookie workflow

The author still takes “simplified” or “traditional” font as an example to illustrate the working process of Cookie.

(1) When we use the browser to visit Jianshu.com for the first time, the simple book server does not know the information of the browser. By default, the content displayed by the browser is “Simplified”. The server creates a Session for the browser.

(2) When we set the content displayed by the browser to “traditional”, we will set local to zh-TW through cookies, send a request to the server, and the response will be to set the content displayed by the browser to “traditional”, and the server will update the Session information to zh-TW (traditional).

(3) when we close the browser, the Session to disappear, and then we open the browser again, found that Jane will still be traditional display content of the book, the author thinks that this is because the server Session Jane book stores the browser should display font, (such as server stores the browser a unique id, then re-open the browser, When making a request to the server, the server sends traditional content based on the previous Session.

The attribute of the Cookie

  • Domain: the Domain of the Cookie; The browser only sends cookies to the server hostname in the specified domain, so the server restricts cookies to a specific domain. Match the jianshu1.jianshu.com and jianshu1.jianshu2.jianshu.com jianshu.com domain, but with js.com did not match.
  • Path: This attribute assigns cookies to specific documents on the server. If the Path attribute is a URL Path prefix, you can attach a Cookie to Path /foo, matching /foobar and foo/bar.html, and Path “/” matching everything in the domain name.
  • Secure: Whether this Cookie is sent only when HTTP uses an SSL connection;
  • Expires: The number of expired seconds since 00:00:00 GMT, January 1, 1970;
  • Name: the name of the Cookie variable;
  • Value: the value of the Cookie variable;

In the iOS NSHTTPCookie

Common attributes:

  • NSHTTPCookieDomain domain: indicates the cookie domain.
  • NSHTTPCookiePath Path: indicates the path of the Cookie.
  • NSHTTPCookiePort portList: indicates the list of Cookie ports.
  • NSHTTPCookieName name: indicates the name of the Cookie.
  • NSHTTPCookieValue value: indicates the value of the Cookie.
  • NSHTTPCookieVersion Version: indicates the version of the Cookie.
  • NSHTTPCookieExpires expireDate: indicates the Cookie expiration date.
  • NSHTTPCookieDiscard sessionOnly: A Boolean value indicating whether cookies should be discarded at the end of the session (regardless of expiration date);
  • HTTPOnly: specifies that clients do not share cookies with JavaScript applications to prevent cross-site scripting attacks;
  • NSHTTPCookieSecure Secure: specifies that cookies will only be used for HTTPS connections and not HTTP connections.
  • Properties: Cookie properties;
  • NSHTTPCookiePropertyKey: defines constants supported in the cookie property dictionary;
  • NSHTTPCookieComment comment: indicates the Cookie description
  • NSHTTPCookieCommentURL commentURL: the description URL of the cookie;
  • NSHTTPCookieAcceptPolicy: Access permission for Cookie. NSHTTPCookie is managed by NSHTTPCookieStorage.
    • NSHTTPCookieAcceptPolicyAlways: store all cookies;
    • NSHTTPCookieAcceptPolicyNever: don’t store cookies;
    • NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain: only save domain values and request the domain matching Cookie;

IOS network requests use cookies

The header of the cookie in the request header of the client, the key is “cookie”

When the server responds to the client, the cookie’s header in the response header is “set-cookie”.

  • Network requests use AFN to carry cookies

To test AFN network request carrying Cookie, the author used to carry Cookie when accessing Juejin. Im, and the effect is shown as follows:

The relevant codes are as follows:

NSString *urlString = @"https://juejin.cn"; AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager]; sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer]; [sessionManager.requestSerializer setValue:@"QiShareNameAFN=QiShareValueAFN; QiShareTokenAFN=QiShareTokenValueAFN" forHTTPHeaderField:@"cookie"]; [sessionManager GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { }];Copy the code

When multiple cookie values need to be set, use cookieKey1=cookieValue1; cookieKey2=cookieValue2; To separate each pair of cookiekeys and values with a semicolon.

  • Network requests use NSURLSession to carry cookies

To test the Cookie carried by NSURLSession network request, the author used the Cookie carried when visiting Jianshu.com, and the effect is as follows:

The relevant codes are as follows:

    NSURL *url = [NSURL URLWithString:@"https://www.jianshu.com"];
    NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
    mRequest.HTTPMethod = @"GET";
    [mRequest setValue:@"QiShareName=QiShareValue;QiShareToken=QiShareTokenValue" forHTTPHeaderField:@"cookie"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:mRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    }];
    [dataTask resume];
Copy the code

The Demo:

For more information, see QiNetwork

Refer to study website

  • rfc6265
  • What’s the difference between cookies and sessions?
  • The Definitive GUIDE to HTTP

Recommended articles:

IOS icon & startup graph generator (a) algorithm small column: “D&C ideas” and “quick sort” iOS avoid common crashes (b) algorithm small column: select sort iOS Runloop (a) iOS common debugging method: LLDB command iOS common debugging method: Breakpoint iOS commonly used debugging methods: static analysis odd dance weekly