Android HTTP Session && Cookie

Source: Internet
Author: User
Tags filetime

Http://www.2cto.com/kf/201206/135471.html
HTTP protocol and status hold

The HTTP protocol itself is stateless, which is consistent with the HTTP protocol's original purpose, the client simply needs to request to the server to download some files, both the client and the server do not need to record each other's past behavior, each request is independent, Like the relationship between a customer and a vending machine or an ordinary (non-membership) hypermarket.

Yet clever (or greedy?) People quickly discovered that providing some on-demand dynamic information would make the web more useful, like adding on-demand functionality to cable TV. This demand on the one hand, forcing HTML to gradually add the form, script, Dom and other client behavior, on the other hand on the server side of the CGI specification in response to the client's dynamic request, as a transport carrier HTTP protocol also added file upload, cookie these features. whichThe purpose of cookies is to solve the problem of stateless defects in the HTTP protocol .。 As for the subsequent appearancesession mechanism is another solution to maintain state between client and server.

Let's use a few examples to describe the difference and connection between a cookie and a session mechanism. I used to go to a coffee shop to drink 5 cups of coffee free of charge for a cup of coffee, but a one-time consumption of 5 cups of coffee is very little, then need some way to record a customer's consumption quantity. Imagine the fact that there are several options below:
1, the shop clerk is very strong, can remember each customer's consumption quantity, as long as the customer walked into the coffee shop, the clerk knew how to treat. This approach is the protocol itself that supports the state.
2, issued to customers a card, the above record the amount of consumption, there is generally a valid period. If the customer presents this card each time it is consumed, the consumption will be linked to the previous or subsequent consumption. This practice is to keep the state on the client.
3, issued to the customer a membership card, in addition to the card number of what information is not recorded, each time the consumer, if the customer presented the card, the shop clerk in the store records found this card number corresponding record add some consumer information. This is done by keeping the state on the server side.

Since the HTTP protocol is stateless and does not want to be stateful due to various considerations, the next two scenarios become a realistic choice. In particular, the cookie mechanism uses a scheme that maintains state on the client, while the session mechanism uses a scenario that maintains state on the server side. We also see that the session mechanism may need to use a cookie mechanism to save the identity, but in fact it has other options because the server-side hold-state scheme also needs to preserve an identity on the client side.

Http://www.blogjava.net/cheneyfree/archive/2007/05/26/120168.html

Cookie Definition
typedef struct COOKIEENTRY
{
Ptchar Pszname;
Ptchar Pszvalue;
Ptchar Pszurlpath;
DWORD dwflags;//security Flags
DWORD Dwlowwordexpiration;//lowword of FILETIME
DWORD Dwhighwordexpiration;//highword Offiletime
DWORD Dwlowwordcreation;//lowword of FILETIME
DWORD Dwhighwordcreation;//highword of FILETIME
CHAR chend;//' * '
}cookieentry, *lpcookieentry;

In summary, each cookie has 6 attributes, namely: Cookie Name, Cookie Value, Domain;path; Secure; Expire Date. The 6 attributes of the cookie given here are not exactly the same as the struct defined in C + +. The reason for this is explained in the file Format section of the cookie.
The following explanations are given for each attribute in the cookie structure:
Cookies Name<KeyThe required attribute, which indicates the name of the cookie, consists of a series of characters (not including parentheses, commas, spaces, etc.), each cookie is represented by a unique name that can contain letters, numbers, and underscores. The name of the cookie is not case-sensitive, so MyCookie and MyCookie are the same. However, considering that the server-side language may be case sensitive, it is best to be case-sensitive to program developers when defining and using them.
Cookies Value,<ValueThe value of the >cookie, the information stored in the cookie by the Web server, and the string value stored in the cookie. This value is encoded with encodeURIComponent () before it is stored, otherwise it loses data or consumes cookies. And the number of bytes added to the cookie name and value cannot exceed 4095 bytes, or 4KB.
Domain, optional, indicates the scope of the cookie's valid domain, the default is the name of the server that generated the cookie, and for security reasons, the Web site cannot access cookies created by other domains. After the cookie is created, the domain information is stored as part of the cookie. For a domain, for example, http://www.baidu.com/view/index.html, its domain is: baidu.com. There is no detail here, and later chapters are covered.
Path, optional, indicates the valid path of the cookie in the valid domain, the Web page outside the valid path cannot read and write the cookie, the default is the URL of the information that generated the cookie, and this property is another security feature of the cookie that restricts access to a specific directory on the Web server. That is, control which accesses can trigger the send. For example, the requested address is the URL above, and if Path=/view, the cookie is sent, but path is a different path, the cookie is ignored.
Secure, optional, an True/false value that indicates whether the cookie can only be accessed from a secure Web site (Web site using SSL and HTTPS protocol), that is, if a cookie is marked as safe (this value is set to true), The cookie is then transmitted only if the client-server conversation channel is secure (for example, HTTP over SSL).
Expire Date, optional, indicates the time that the cookie is valid, and once it expires, the cookie will no longer be valid, usually specified by the program that generated the cookie (date indicated by the server), and if not specified, the default cookie will expire automatically after the end of the user session.



The difference between the cookie mechanism and the session mechanism
*********************************************************************************** * * The
Cookie is the client's storage space, maintained by the browser. In particular, the cookie mechanism uses a scheme that maintains state on the client, while the session mechanism uses a scenario that maintains state on the server side. At the same time, we also see that because the server-side state-preserving scheme also needs to preserve an identity on the client side, the session mechanism may need to use the cookie mechanism (" How to implement automatic logon
*************************************************************************************
When a user registers with a website, they receive a cookie for a unique user ID sent by the server. When the customer later reconnect, the user ID is automatically sent back to the server, the server checks it, determines whether it is a registered user and chooses automatic login, so that the user Service needs to give an explicit user name and password, you can access the resources on the server.
How to customize the site based on the user's hobby
*************************************************************************************
The website may use cookies to record users ' wishes. For simple settings, the site can store the settings of the page directly in a cookie to complete the customization. For more complex customizations, however, the site simply sends a unique identifier to the user, and the server-side database stores the page settings for each identifier.

enable session hold via Cookie
/http l62s.iteye.com/blog/1663113

Click ( here) to collapse or open

  1. Import java.io.IOException;
  2. Import java.io.UnsupportedEncodingException;
  3. Import java.util.List;
  4. Import org.apache.http.HttpEntity;
  5. Import Org.apache.http.HttpResponse;
  6. Import Org.apache.http.HttpStatus;
  7. Import Org.apache.http.NameValuePair;
  8. Import org.apache.http.client.ClientProtocolException;
  9. Import Org.apache.http.client.CookieStore;
  10. Import org.apache.http.client.entity.UrlEncodedFormEntity;
  11. Import Org.apache.http.client.methods.HttpPost;
  12. Import Org.apache.http.cookie.Cookie;
  13. Import org.apache.http.impl.client.DefaultHttpClient;
  14. Import Org.apache.http.protocol.HTTP;
  15. Import Org.apache.http.util.EntityUtils;
  16. public class Myhttpclient implements Inetconfig {
  17. Private Defaulthttpclient httpClient;
  18. Private HttpPost HttpPost;
  19. Private Httpentity httpentity;
  20. Private HttpResponse HttpResponse;
  21. public static String PHPSESSID = null;
  22. Public Lvhttpclient () {
  23. }
  24. public string executerequest (string path, list<namevaluepair> params) {
  25. String ret = "None";
  26. try {
  27. This.httppost = new HttpPost (basepath + path);
  28. httpentity = new Urlencodedformentity (params, HTTP. UTF_8);
  29. Httppost.setentity (httpentity);
  30. The first time is generally not yet assigned, if there is a value will be SessionID sent to the server
  31. if (null! = PHPSESSID) {
  32. Httppost.setheader ("Cookie", "phpsessid=" + phpsessid);
  33. }
  34. HttpClient = new Defaulthttpclient ();
  35. } catch (Unsupportedencodingexception e) {
  36. E.printstacktrace ();
  37. }
  38. try {
  39. HttpResponse = Httpclient.execute (HttpPost);
  40. if (Httpresponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {
  41. httpentity entity = httpresponse.getentity ();
  42. ret = entityutils.tostring (entity);
  43. Cookiestore Mcookiestore = Httpclient.getcookiestore ();
  44. list<cookie> cookies = mcookiestore.getcookies ();
  45. for (int i = 0; i < cookies.size (); i++) {
  46. Here is the value of reading cookie[' PHPSESSID ') exists in a static variable, guaranteed to be the same value each time
  47. if ("Phpsessid". Equals (Cookies.get (i). GetName ())) {
  48. PHPSESSID = Cookies.get (i). GetValue ();
  49. Break
  50. }
  51. }
  52. }
  53. } catch (Clientprotocolexception e) {
  54. E.printstacktrace ();
  55. } catch (IOException e) {
  56. E.printstacktrace ();
  57. }
  58. return ret;
  59. }
  60. }

Based on the HTTP protocol, then if the site is not PHP, the cookie called SessionID may be called something else, it is not PHPSESSID, it is called another name, this may be specific to the case to check.

HTTP protocol Analysis:
http://blog.csdn.net/gueter/article/details/1524447

Android HTTP Session && Cookie

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.