The reception and sending of Android cookies

Source: Internet
Author: User
Tags send cookies

I was doing automatic login when I encountered the pit, close-up this article to remind you not to go around.

We all know that cookies on the web side can be saved by server-side settings, by default, the cookie is cleared by closing the browser, but you can set the cookie's expiration date on the server side, and the browser will automatically save the cookie. And on Android is not automatically save cookies, I use OKHTTP3, I can not find Response.addcookie (cookie) and Request.getcookies () method (Java Web operation), If you do not save and re-send cookies to the server, it is not automatically logged in. Most of the geniuses knew it was all in the head.

If it's Okhttp3, that's it.

Cookies in the log output

In this way we have already got the cookie, the next is to save the cookie, write the following static method to save the cookie to sharedpreferces, my design idea is to try to operate the database as little as possible.

1  Public Static FinalString islogined = "islogined";2  Public Static FinalString cookie = "Cookie";3  4 5  Public Static voidsavecookiepreference (context context, String value) {6Sharedpreferences preference =context.getsharedpreferences (islogined, context.mode_private);7Sharedpreferences.editor Editor =Preference.edit ();8 editor.putstring (COOKIE, value);9 editor.apply ();Ten  One}

Then call this method to save the cookie

Then write a method to get the value of the cookie in sharedpreferces

 Public Static String getcookiepreference (context context) {    = context.getsharedpreferences (islogined, context.mode_private);     = Preference.getstring (COOKIE, "");     return

The last thing to do is to bring a cookie on each request, and this cookie is placed in the head.

This allows for automatic login.

The reception and sending of Android cookies

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.