Cookie, Session, token that's the thing.

Source: Internet
Author: User
Tags http request
Cookie, Session, token that's the thing.

Author: Riding a pig to see a meteor

Links: https://www.jianshu.com/p/bd1be47a16c1


Introduction: The use of cookies in the new company project, in the major Android technology discussion group to the predecessors to discuss the cookie, session, token of the three buddies, many developers say that the words have been seen, so it is time to review the HTTP basis and summarize the development experience. This paper focuses on the basic concepts and application scenarios of cookie, Session and token in the analysis of Popular science, and the use of cookies under the Okhttp framework. If the article does not write well, please the developers of the old driver private chat or in the comment area pointing out issue.


1 What is a cookie.


Cookie technology comes from the rapid development of HTTP protocol on the Internet. With the advent of the Internet era, bandwidth and other restrictions do not exist, people need more complex internet interaction activities, it is necessary to maintain active status with the server (short: keepalive).


Therefore, in the early stage of the browser development, in order to adapt to the needs of users of the technical introduction of a variety of Web browsing to maintain the state of the means, including the Cookie technology. A cookie is a text file stored in a browser directory on a computer that is stored in RAM when the browser is running (a cookie called a Session cookie) that can be stored on the user's local hard drive once the user exits from the site or server. (This type of cookie is called a persistent cookie).


Cookie Origin: In 1993, Netscape employee Lou Montulli invented the widely used Cookie today in order to allow users to further improve their access to a website and to further implement a personalized network. (So, appropriate laziness will also promote the development of human computers a small step ~)


Cookie timeliness: Some cookies are currently temporary and some are ongoing. The temporary cookie is only stored on the browser for a specified period of time, and once the specified time is exceeded, the cookie is purged by the system.


Cookie usage Restrictions: Cookies must be set before the content output of the HTML file, and different browsers (Netscape Navigator, Internet Explorer) do not treat cookies differently and must be considered when used The cookie cannot be established if the client user sets a block cookie. And on the client side, a browser can create a maximum of 300 cookies, and each cannot exceed 4KB, each WEB site can set the total number of cookies cannot exceed 20.


Execution process:


A: First, the client sends an HTTP request to the server side.

B: After the server accepts the client request, it sends an HTTP response to the client, which contains the Set-cookie header.

C: Second request initiated on the client (note: If the server requires us to bring a cookie, we need to take the cookie on the B-step and initiate a second request as the request header), providing the server-side information that uniquely identifies the client. At this point, the server side can also determine whether the client has enabled cookies. Although the user may suddenly disable the use of cookies in the course of interacting with the application, this situation is largely unlikely to occur, so it can be considered without consideration, which in practice proves to be right.


For ease of understanding, you can first look at this process execution diagram deepening concept



So, the request headers and cookies on the browser are there. The following figure captures one of them.



So, it's all about cookies on the browser, so how do we manage and use cookies in Android development?


Okhttp as a classic to explode network framework, its API (this article is based on the Okhttp3.0 version above, 3.0 below the version of the API is different) is through the okhttpclient in the Cookiejar or interceptors to manage cookies. In theory, we simply set up the Cookiejar or interceptors when we build the singleton okhttpclient, and then the specific operation (the specific action is to save the cookie, take the cookie), the OKHTTP framework will help us to automatically manage the cookie.


The following figure:



This is one of the features of the collection that can help us manage cookies simply and effectively. But we still have to go through the source code to explore. First, Cookiejar is an interface.



The translation of English Notes is (corresponding paragraph translation):

Cookiejar This interface provides powerful support and related strategies for HTTP cookies.


The implementation of this strategy will be responsible for choosing to accept and reject those cookies. A reasonable strategy is to deny all cookies, although this interferes with the session-based self-authentication scheme that requires cookies.


As a cookie persistence, the implementation of this interface must also provide the storage of cookies. A simple implementation can store cookies in memory, and a complex system can use a file system to hold a database of accepted cookies. The link here https://tools.ietf.org/html/rfc6265 specifies the cookie policy that stores model updates and expired cookies.


So, Okhttp's source tells us that we can store cookies in memory, and that a complex system can use a file system to hold a database of accepted cookies. As a result, we can simply manage and use the map.

Continue to analyze the method inside the Cookiejar interface, still on the source code



There's a way. One is savefromresponse (httpurl URL, List cookie), loadforrequest (httpurl URL)


Savefromresponse method Translation: Depending on the method of this jar, you can save the cookie from an HTTP response here.


Note that if you respond, this method may be called a second HTTP response, including a trace. For this stealth HTTP feature, the cookie here contains only the cookie that it tracks. The simple point of understanding is that if we use this method, it will be traced (in short, after the client request succeeds, in the response header to save the cookie)


Loadforrequest method Translation: Loads a cookie from this method into an HTTP request to the specified URL. The result that this method returns from the network may be an empty collection. A simple implementation will return an accepted cookie that has not yet expired to match. (It is plain that the URL is loaded with a cookie on the request header).



In this way, we can complete the non-persistence of cookies with the above code. What, non-permanence, this is God horse.


Continue to the popular science, said in the above, the cookie is timeliness, so, the management of the cookie is divided into persistent cookie and non-persistent cookie. Non-persistent cookies are stored in memory, which means that their lifecycle is basically consistent with the app and the cookie is lost after the app is closed. Persistent cookies are stored on a local disk and are not lost when the app is closed. So, if we want to use the cookie persistence strategy, the idea can refer to the above non-persistent policy, just need to change the storage mode:


A: Remove the cookie from the response and save it locally via the response blocker, remove the cookie locally from the request blocker and add it to the request

B: Custom Cookiejar, save cookies locally in Savefromresponse (), remove cookies locally from loadforrequest ().


So here's how to make persistent cookie operation by okhttp the high-value interceptor.


Save Cookie Blocker-1


Save Cookie Blocker-2


The implementation of this Savecookiesinterceptor interceptor is to first get the value of the Set-cookie field from response and then save it locally via sharedpreferences.


Add a cookie to the request header


Addcookiesinterceptor Request Interceptor, the purpose of this interception is to determine if the request has a cookie, it is added to the header of the cookie.

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.