How to implement cookie handling on Android using OkHttp?

后端 未结 3 1749
一生所求
一生所求 2020-11-27 12:06

Using OkHttp by Square https://github.com/square/okhttp, how can I:

  1. Retrieve a cookie returned from the server
  2. Store the cookie for upcoming requests<
3条回答
  •  误落风尘
    2020-11-27 12:47

    Pre OkHttp 3, you can pass a CookieHandler to your OkHttpClient instance. You can use the CookieManager implementation from java.net or you could implement your own if you want. Choose the policy that works best for your needs.

    OkHttpClient client = new OkHttpClient();
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    client.setCookieHandler(cookieManager);
    

    OkHttp will save cookies received from Responses into the CookieHandler and read from it when sending requests. It will do so for matching request/response URIs.

提交回复
热议问题