Android Localized storage cookie (for httpclient)

Source: Internet
Author: User

Because recently someone asked me how to save httpclient cookies, so write down here, and by the way record summary. Of course, with the Android network programming experience of children's shoes at a glance to understand La ~


Not much to say, directly on the code:

/**     * Local Storage Cookie     * @param response     *    /private void Savecookies (HttpResponse response) {        Sharedpreferences preferences = getsharedpreferences ("cookies", mode_private);        list<cookie> thecookies = Client.getcookiestore (). GetCookies ();        StringBuffer sb = new StringBuffer ();        for (int k=0; k<thecookies.size (); k++)        {            log.e ("Loop Get cookie Information", "name =" + Thecookies.get (k). GetName ());            LOG.E ("Loop Get cookie Information", "value =" + Thecookies.get (k). GetValue ());            Sb.append (Thecookies.get (k). GetName () + "=" + Thecookies.get (k). GetValue () + ";");        Date date = Thecookies.get (0). Getexpirydate ();        LOG.E ("The valid time of the cookie is", Format.format (date));        Preferences.edit (). putstring ("Cookies", sb.tostring ()). commit ();    }

Set Cookies:

String url = "Http://www.host.com/test";            HttpGet get = new HttpGet (URL);            Sharedpreferences sharedpreferences = getsharedpreferences ("cookies", mode_private);            Get.setheader ("Cookies", sharedpreferences.getstring ("Cookies", "" "));            Try            {                HttpResponse response = Client.execute (get);                httpentity entity = response.getentity ();                if (Response.getstatusline (). Getstatuscode ()! = Httpstatus.sc_ok)                {                    log.e (TAG, "Save Failed");                    //...                }                else                {                    log.e (TAG, "Save succeeded");                    //...                }            }            catch (Exception e)            {                e.printstacktrace ();            }

This allows you to avoid duplicate HTTP requests, such as repeating logins, even after you exit the app and reuse the cookie the next time. Note, however, that a cookie is valid for a period of validity and will not be valid if it is more than the expiration date, and requires a login to perform other operations. As in the above code, the test cookie is valid for one months.


Therefore, in the use of cookies, you can also save the validity period of the cookie, of course, do not save or can, carry invalid cookie to access is the server will naturally return the corresponding prompt, according to the prompt response. In addition chit chat when chit chat when, cookie is a very simple text data, record the server and client access information, so read and storage, management efficiency is very high, but the bad is not enough security, localized storage is best to pay attention to security. Of course, if it is not a very important data, and has good usage habits, it is nothing.



The above is httpclient for the Android development environment, if you are using other Apache httpclient jar packages, such as Commons-httpclient-3.1.jar. May find that the above method is not convenient to use, then we can also imitate the browser processing cookie policy, using the unique Httppost.setrequestheader () method in the jar package to add access information, such as

Httppost.setrequestheader ("Host", "host Address");

Httppost.setrequestheader ("Connection", "keep-alive");

Httppost.setrequestheader ("Cookie", cookie);

Httppost.setrequestheader ("User-agent", useragent);


We then use the grab Bag tool to look at a request from a computer browser and see the cookie data in a similar format in headers (a request to visit a Youdao website):


Visible, this approach is similar to the browser's strategy.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Localized storage cookie (for httpclient)

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.