WebView HttpClient How to keep conversation session unified

Source: Internet
Author: User
Tags http cookie set time setcookie nginx server

The cookie session is displayed in the form of key---value, 1. The session is stored on the server side, and there is a section of the control store user information, mainly to determine whether the user is logged in, when the client uses Httpclient/httpurlconnection for login requests, pass the past Username= " CCC "service side of the session to determine whether there is a change SessionID, and value, does not exist on behalf of the user has not logged in, the server will automatically generate a unique SessionID it is key, passed the CCC is value,key=." SessionId "Value=" CCC ", the next time the request for HTTP request after the request header will take this sessionId to the server side of the session storage area to determine whether to log in, log on the return success, not logged in the new allocation. Judging similar to the map collection, passing Map.get (sessionId) is equal to the CCC.     2. Question: What does cookie management look for in httpclient? 3. Cookiemanager is a management WebView, the session is stored in the cookie, httpclient log on to the server, Remove SessionID from the HTTP cookie into WebView (sync cookie), WebView access to the business, the server will assume that the user is logged in because of SessionID consistency. Cooki's acquisition:
1 12 234 cookiemanager cm = cookiemanager.getinstance (); 5 String cookiestr = Cm.getcookie (URL);

Synchronization of Cookies:
1 synchronization of Cookies: 2 3 4 cookiesyncmanager.createinstance (this); 5 6 7 cookiesyncmanager.getinstance (). sync ();
Clear cookies:
1 Clear Cookies: 2 3      cookiemanager.getinstance (). Removesessioncookie (); 4    or:5 cookiemanager.getinstance (). Removeallcookies ();
As long as allow JS can not be synchronized successfully. The reason may be that JS is allowed to get data across domains through Ajax. It may be safe to consider that httpclient and webview need to share cookies because if you do not share, then assume that you are logged in httpclient and then use the WebView to open the page after login.
  1. 1-Defaulthttpclient httpclient=....;2-String tourl= "https://cap.cityu.edu.hk/studentlan/details.aspx ...";3-4-List<cookie> cookies =Httpclient.getcookiestore (). GetCookies ();5-6-if(!Cookies.isempty ()) {7-Cookiesyncmanager.createinstance ( This);8-Cookiemanager Cookiemanager =cookiemanager.getinstance ();9-//Sync all the cookies in the httpclient with the WebView by generating cookie stringTen- for(Cookie cookie:cookies) { One-String cookiestring = cookie.getname () + "=" + cookie.getvalue () + "; Domain= "+Cookie.getdomain (); A-Cookiemanager.setcookie (Tourl, cookiestring); --cookiesyncmanager.getinstance (). sync (); --     } the- }

1 sharedpreferences SPF = getsharedpreferences ("Cookie", context.mode_private); 2         Cookiesyncmanager.createinstance (this); 3         Cookiemanager Cookiemanager = cookiemanager.getinstance (); 4         String cookiestring = spf.getstring ("cookiestring", "" "); 5         cookiemanager.setcookie (URL, cookiestring); 6         cookiesyncmanager.getinstance (). sync (); 7 8         Webview.loadurl (URL);

1    Public Static voidAddlogincookie () {2         //after successful login, reset the Webviewcookie information to keep the session consistent .... Start , .....3 cookiesyncmanager.createinstance (App.getinstance (). Getapplicationcontext ());4Cookiemanager Cookiemanager =cookiemanager.getinstance ();5 6list<cookie> cookies =app.getpersistentcookieslist ();7          for(inti = 0; I < cookies.size (); i++) {8Cookie cookie =Cookies.get (i);9String cookiestring = cookie.getname () + "=" + cookie.getvalue () + "; Domain= "+Cookie.getdomain ();Ten Cookiemanager.setcookie (Urlset.cookiedomain, cookiestring); One         } A  - cookiesyncmanager.getinstance (). sync (); -         //...... ..... ... .... ... end of the ..... .....???????????? ?????????????????. the}

Reference link http://www.cnblogs.com/sharpxiajun/p/3395607.html The concept of the 1.1 session in computer jargon: A session is an interval between an end user's communication with an interactive systemThis usually refers to the elapsed time between the registration system and the logoff system and, if necessary, a certain amount of operational space. Specific to the Web application of the session, we have done web development, here I do not put forward the definition of the session in the Web, first and everyone to talk about the technical background and the session. Early Web applications or early sites are a kind of static resources to deal with the site, the main function is to view the document, look at the picture, and now the Web application and early differences have been very large, the Internet site more accurate definition should be the Internet software is the website is software, The website represents the software and the definition of the early software is not the same, the early software is running in a single machine environment, and the popularity of the internet to the software and network technology integration, which requires that the website represents the software should have a memory function for transaction processing, transaction processing memory function is what we often say to have state. The core HTTP protocol to implement Web application technology is a stateless protocol, HTTP this design may be a legacy problem, perhaps stateless HTTP is the simplest and most effective means of communication, but when the site becomes software, the state of the maintenance is a very important function. So in Web application development There is the technology to keep the HTTP link state: One is the cookie technology, the other is the session technology. Cookie Technology is the client's solution(Of course, with the advent of HTML5, more robust and secure technology than cookies appear, but given that HTML5 is not enough to be discussed in this article), a cookie is a special message sent to the client by the server, which is stored as a text file in the client, The client then takes these special messages each time it sends a request to the server. Let's say something more specific: when a user accesses a Web site that supports cookies by using a browser, the user provides personal information including the user's name and submits it to the server, and the server sends back the personal information when it sends the corresponding hypertext to the client ., of course, this information is not stored in the HTTP response body (Response body), but is stored in the HTTP response header (Response header), when the client browser receives a response from the server, the browser will store this information in a unified location, For the Windows operating system, we can find stored cookies from: [System disk]:\documents and settings\[user name]\cookies directory; Since then, when the client sends a request to the server, it will send the corresponding cookie back to the server again. This time, the cookie information is stored in the HTTP request header.。 With the implementation of a technology like cookies, after receiving a request from the client browser, the server is able to generate the client-specific information by analyzing the cookie stored in the request header, which dynamically generates the content corresponding to that client. Usually, we can see the "Please remember Me" option from the login screen of many websites, if you check it and then log in, then the next time you visit the site will not need to repeat the tedious login action, and this feature is implemented through cookies.session technology is the service-side solution, it is through the server to maintain state。 Since the term session contains a lot of semantics, it is necessary to clarify the meaning of the session here. First of all, we usually translate the session into a conversation, so we can put a series of interactions between the client browser and the server is called a Session。 From this semantics, we will refer to the duration of the session, which will refer to what is done during the session and so on; , session refers to the server-side storage space for the client, where the information stored is used to hold the state。 From this semantics, we will refer to what is stored in the session, how to get the matching content from the session according to the key value. To use the session, the first step is of course to create a session. So when is the session created? Of course it's still in server-side programs are created during the run, different languages implement applications that have different methods for creating sessions, whereas in Java they are created by calling HttpServletRequest's GetSession method (using True as a parameter). when the session is created, the server generates a unique session ID for the session, and the session ID is used to regain the session that was created in the subsequent request, and after the session is created, You can call the session related methods to add content to the session, which will only be saved in the server, sent to the client only session ID, when the client sends the request again, the session ID will be taken, Once the server accepts the request, it will find the corresponding session based on the session ID, which is used again. Formally, the state of the user is maintained. From this we can conclude that session is a service-side solution to solve the problem of stateless HTTP protocol, which can make a series of interactive actions of client and server become a complete transaction., can make the website become a real meaning software. 1.2 The relationship between a cookie and a sessionAlthough the cookie and session scheme belong to the client and the server, but the implementation of the session on the server is dependent on the cookie of the client, I mentioned Server execution session mechanism will generate the session ID value, this ID value will be sent to the client, the client each request will put this ID value to the HTTP request header sent to the server, and this ID value in the client will be saved, the storage container is a cookie , so when we completely ban the browser's cookie, the server session will not be normal use (note: Some data said that ASP to solve this problem, when the browser cookie is banned, the server session can still be normal use, ASP I have not tried, But for many web sites written in PHP and JSP, I found that the ban on cookies, the site of the session is not normal access) the principle of 1.3 session implementation          java Web containers All implement the session mechanism, the logical idea is consistent, but the specific scheme may have some differences, Here I take the Tomcat container as an example to explore the implementation of the next session of the Mechanism. is the Tomcat source session implementation:             The path to implement the package is: Org.apache.catalina.session,tomcat external to provide a session call interface is not in this implementation package, the external interface is under the package Javax.servlet.http HttpSession, and implement the standards in the package Ession is a standard implementation provided by Tomcat, and of course external Tomcat does not want users to manipulate standardsession directly, but instead provides a Standardsessionfacade class, The component of the session in the Tomcat container is the servlet, and the servlet operation session is done through Standardsessionfacade, This prevents the programmer from directly manipulating the security issues that Standardsession brings. (Standardsessionfacade uses the Fa?ade (appearance) mode in design mode, which allows components of different logic layers to be decoupled). The class with manager in the   implementation class is the tool class used to manage the session, which is responsible for creating and destroying session objects, where Managerbase is the base class for all session management tool classes and is an abstract class. All classes that implement the session management function inherit this class, which has a protected method, which is the method of creating the SessionID value (the mechanism for the ID value generation of the session of Tomcat is a random number plus time plus the JVM ID value, The ID value of the JVM is calculated based on the server's hardware information, so the ID values of the different JVMs are unique, and the Standardmanager class is the default session management implementation class in the Tomcat container. It stores the session information in the memory of the server where the Web container resides. Persistentmanagerbase is also the inheriting Managerbase class, which is the base class for all persisted stored session information, Persistentmanager inherits persistEntmanagerbase, but this class is just a static variable and a GetName method, which does not seem to be significant at present, for the persistence of storage Session,tomcat also provides a storebase abstract class, which is the base class for all persisted storage sessions , and Tomcat also gives the file storage Filestore and data storage Jdbcstore two implementations.   1.4 Problems in the actual application of the session             by the session implementation mechanism described above, we will find that in order to compensate for the stateless features of the HTTP protocol, The server consumes a certain amount of memory and CPU overhead for storing and processing session calculations, which is one of the reasons that Tomcat's web container's concurrent connections are so low (the default number of connections in the Tomcat Official document is 200). Therefore, many Java language Web sites, in the production environment before the Web container will add a static resource server, such as: Apache server or Nginx server, static resource server does not solve the HTTP stateless problem function, Therefore, the server that deploys the static resources will not give up memory or CPU compute resources to deal with functions such as session, which can handle each HTTP request more efficiently, so the number of concurrent connections of the static resource server is higher. So we can make those requests that have no status to keep the request directly in the static server processing, and to carry out the status of the request is in the Java Web container processing, so as to better improve the efficiency of the site.             Current Internet sites to improve website security and concurrency, the number of servers deployed on the server is often greater than or equal to two units, The service provided by multiple servers is equivalent, but different servers will certainly have different web containers, from the above tells us that the implementation mechanism of the session is the internal mechanism of the Web container, which results in a Web container generated in the session ID value is different, So when a request to a server, the browser gets a response, the client is stored on the a server generated by the session ID, when another request is distributed to the B server, B Server Web container is not recognized this session ID value, There will be no record of this sessionid information, this time requires two different web containers to synchronize the session. The Tomcat container has an official solution that is to use the APACHE+TOMCAT+MOD_JK scheme, which broadcasts to another Web container when the information of the session in a Web container changes. When another Web receives a broadcast, it synchronizes the session information to its own container, which consumes system resources, and when traffic increases, it can seriously affect the efficiency and stability of the website.            &NBsp   I now do the site has a solution, when the user requests the site will first send the request to the hardware load balancer device, the device can intercept the client sent over the session ID value, and then we based on this ID value to find the server that generated the session, Send the request directly to this server. This solution seems to solve the session sharing problem, in fact, the result is the cluster system eventually changed back to a single point system, if the processing request of the Web container hangs, then the user's related session operation is discarded. In addition, this approach interferes with the load balancing calculation of the load Balancer server, so that the distribution of the request is not fair.   General large-scale Internet company's website are composed of independent channels, such as the Baidu we commonly used, there will be Baidu search, Baidu Music, Baidu Encyclopedia and so on, I believe they will not give these different channels to a development team to complete, should each channel is an independent development team, Because each channel application is a standalone Web application, there is a cross-site session synchronization problem, cross-site logins can use a single sign-on (SSO) solution, but no matter what solution, cross-site session sharing is still a problem to avoid.  1.5 Technical solution for solving session related problems The session has two problems that need to be solved: 1) session storage should be independent of the Web container, but also independent of the server that deploys the Web container, 2) How to perform efficient session synchronization.   Before we talk about solving these problems, we should first consider how the next session is efficient, is there a memory, a file, or a database? Files and databases are stored in the session data is cured to the hard disk, the way to operate the hard disk is that the efficiency of the io,io operation is much lower than the operating memory of the data, so the file and database storage method is not desirable, so the session data stored in memory is the best choice. Therefore, the best solution is to use distributed cache technology, such as: Memcached and Redis, to separate the session information storage is also a way to solve the session synchronization problem. Tomcat session synchronization also has the use of memcache solution, you can participate in the following article:  Http://blog.sina.com.cn/s/blog_ 5376c71901017bqx.html But this solution only solves the synchronization problem, the session mechanism is still tightly coupled with the Web container, we need an efficient and scalable solution, then we should not simply separate the session to store, but design a completelyThe session mechanism, which can provide each Web application with the function of the session and can achieve session synchronization, the following is a zookeeper implementation of the distributed session program: http://blog.sina.com.cn/s/ blog_5376c71901017bqx.html  own understanding:       When the client first accesses the server, the HTTP request header is empty, the server detects and responds, If it is empty then return the corresponding session and the corresponding unique SessionID, because the session is the client based on the HTTP protocol (stateless connection) through the session and the cookies are automatically set, the next time the client makes HTTP requests, Incoming cookies in the request header, the server automatically obtain and verify, if it is a simple browser, in the verification SessionID and the server set time-out compared to the timeout, if the time-out directly pull the login, not timed out and consistent then jump into the appropriate interface to obtain relevant information.   Because HTTP is a stateless protocol, cookies are designed to address the state of the HTTP protocol's stateless flaws. Session mechanism is a solution for maintaining state between client and server    reference link:http://blog.csdn.net/axin66ok/article/details/6175522 1.cookie is a text string handle sent to the client's browser and saved on the client's hard disk (with a valid expiration date) that can be used to persist data between sessions of a Web site. 2.session In fact refers to the time when a visitor arrives from a particular homepage to the point of departure. The session actually uses cookies to process information, and when the user first makes a request, the server creates a cookie on the user's browser, which in fact means that the cookie expires when the session ends. Note: The name of the cookie created for this user is ASPSessionID. The only purpose of this cookie is to provide a different identity for each user.the common point of 3.cookie and session is that both cookies and sessions are used to track the user's identity in a browser.  the difference between the 4.cookie and session is that the cookie data is stored on the client and the session data is saved on the server side. Simply put, when you log in to a website:

· If the Web server side uses the session, then all the data is stored on the server, the client each time the server is requested to send the current session of the SessionID, the server according to the current SessionID to determine the corresponding user data flag, To determine whether the user is logged on or has some kind of permission. Since the data is stored on the server, you can't forge it, but if you can get the SessionID of a logged-on user, it can be successful to forge the user's request with a special browser. SessionID are randomly assigned when the server and client link are not duplicated in general, but if there is a large number of concurrent requests, there is no possibility of duplication .

· If the browser is using a cookie, then all the data is stored on the browser side, such as when you log in, the server set the cookie user name, then when you request the server again, the browser will send the user name piece to the server, these variables have a certain special tag. The server is interpreted as a cookie variable, so as long as the browser is not closed, the cookie variable is always valid, so it can be guaranteed for a long time without dropping the line. If you can intercept a user's cookie variable and then forge a packet to send the past, the server still thinks you're legit. Therefore, the use of cookies is more likely to be attacked. If it is set to a valid time, then it will save the cookie on the client's hard disk, the next time you visit the website, the browser first check whether there is a cookie, if any, read the cookie, and then sent to the server. If you save a forum cookie on a machine that is valid for one year, if someone invades your machine, copies your cookie, and places it under the directory of his browser, then he or she logs in as your identity. So a cookie can be forged. Of course, the forgery of the need for ideas, directly copy the cookie file to the cookie directory, the browser is not recognized, he has a index.dat file, stored the cookie file set up time, and whether there is modification, so you must first have to have the site of the cookie file, And to cheat the browser from the guaranteed time .

5. Two can be used to store private things, also have the term of validity, the difference is that the session is placed on the server, the expiration depends on the service period setting, the cookie is a client, the past or not can be set in the time of the cookie generation.

(1) The cookie data is stored on the client's browser and the session data is placed on the server
(2) Cookies are not very safe, others can analyze cookies stored locally and cookie spoofing , if the main consideration is that security should use the session
(3) The session will be stored on the server for a certain period of time. When the increase in access, will be compared to occupy your server performance, if the main consideration to mitigate server performance, you should use cookies
(4) The limit of a single cookie on the client is 3K, that is, the cookie stored by a site at the client cannot be 3 K. (5) Therefore: the login information and other important information stored as a session; Other information can be placed in a cookie if it needs to be retained

WebView HttpClient How to keep conversation session unified

Related Article

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.