An easy way for Android to use Okhttp/retrofit to persist cookies

Source: Internet
Author: User



First of all, the cookie is not much to say, or do not know the words recommended to see this article
Cookie/session mechanism detailed
Deep analysis of Cookie technology



Why persist cookies is not much to say, you can see this article on behalf of you have this requirement.



A cookie is simply a pair of key-value pairs that the server stores in the client, such as an earlier shopping cart, which keeps the login state as a cookie.
However, the functionality of cookies is browser-dependent , and most browsers have the ability to manage cookies. Of course, you can also disable this function by setting, after all, cookies are very easy to disclose the user's privacy



It also says that the cookie function relies on the client, and it is clear that we have to manage cookies manually while developing the app.




Before persisting the cookie, we'd better understand how the cookie is transmitted, and then I think you'll be able to use a very simple way to keep the cookie.

 
1. How the cookie is transmitted 


Cookies use Httpheader to pass data.
The cookie mechanism defines two types of headers: the Set-cookie header and the cookie header.



The Set-cookie header is contained in the response header (Responseheader) of the Web server
The cookie header is contained in the browser client request header (Reguestheader)



The operation of the cookie, the specific analysis is as follows


2. Simple and brutal way to persist cookies


The method is derived from this http://tsuharesu.com/handling-cookies-with-okhttp/



After seeing how the cookie is transmitted, we can persist the cookie in a simple way, by manually writing a cookie to the header or obtaining a cookie via Okhttp's Intercept method.


 
/**
 * This interceptor put all the Cookies in Preferences in the Request.
 * Your implementation on how to get the Preferences MAY VARY.
 * <p>
 * Created by tsuharesu on 4/1/15.
 */
public class AddCookiesInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        HashSet<String> preferences = (HashSet) Preferences.getDefaultPreferences().getStringSet(Preferences.PREF_COOKIES, new HashSet<>());
        for (String cookie : preferences) {
            builder.addHeader("Cookie", cookie);
            Log.v("OkHttp", "Adding Header: " + cookie); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
        }

        return chain.proceed(builder.build());
    }
}
/**
 * This Interceptor add all received Cookies to the app DefaultPreferences.
 * Your implementation on how to save the Cookies on the Preferences MAY VARY.
 * <p>
 * Created by tsuharesu on 4/1/15.
 */
public class ReceivedCookiesInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());

        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            HashSet<String> cookies = new HashSet<>();

            for (String header : originalResponse.headers("Set-Cookie")) {
              cookies.add(header);
            }

            Preferences.getDefaultPreferences().edit()
                    .putStringSet(Preferences.PREF_COOKIES, cookies)
                    .apply();
        }

        return originalResponse;
    }
}
/**
 * Somewhere you create a new OkHttpClient and use it on all your requests.
 */
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(new AddCookiesInterceptor());
okHttpClient.interceptors().add(new ReceivedCookiesInterceptor());


Simple cookie Persistence You can create a singleton client in this way, using the client request interface globally. Of course you can also reset intercept every time you new client ...



Also keep in mind that the cookie is for the domain name store. For example: www.baidu.com and image.baidu.com store cookies are not the same ...
If your app really needs to access two domain interfaces at the same time, and two need to persist cookies, remember to make judgments (such as storing cookies in sharepreference as key). Otherwise, two domain name cookies will cover each other ...


3. ontology here, okhttp 3.0 Cookie Management


Related principles can look at this article OKHTTP3 the management and persistence of cookies



Then, the persistent management cookie can be used directly from the open Source Library, simply to explode ...
Https://github.com/franmontiel/PersistentCookieJar



Of course, you can also use the okhttputils of the Great God of Hon Yang, which also provides a persistent management tool for cookies. It's as convenient as the top.



An easy way for Android to use Okhttp/retrofit to persist 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.