Solution of not maintaining Cookie by default in OkHttp3

  • 2021-09-05 00:56:27
  • OfStack

cookies in OKhttp3


OkHttpClient client = new OkHttpClient().newBuilder().cookieJar(new CookieJar() {

   private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

   @Override
   public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
    cookieStore.put(url.host(), cookies);
   }

   @Override
   public List<Cookie> loadForRequest(HttpUrl url) {
    List<Cookie> cookies = cookieStore.get(url.host());
    return cookies != null ? cookies : new ArrayList<Cookie>();
   }
  }).build();

It is mainly to implement CookieJar interface, when OkHttpClient is built.

OkHttp3 does not maintain the solution of Cookie by default

OkHttpClient declared by OkHttp3 does not save Cookie and does not send Cookie by default. In actual development, Session and ID will be lost, which makes the server unable to judge the login status of the current user. After consulting various materials, the solutions are given.

Three concepts:

The first time a connection is established with the server, the server generates an SessionID token for the current connection session. (HTTP is a connectionless protocol)
When the client request, the Cookie with SessionID is sent to the server as a session token.
In actual use of OkHttp3, one Application usually uses only one OkHttpClient instance to connect.

Solution:

Build the CookieJar object and override the saveFromResponse and loadFromRequest methods.

The Http connection is sent and received using the OkHttpClient instance where CookieJar is constructed.

This procedure uses singleton pattern to construct OkHttpClient instance, and Cookie persistence code is as follows:


mOkHttpClient = new OkHttpClient.Builder()
    .cookieJar(new CookieJar() {
     private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

     @Override
     public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
      cookieStore.put(url.host(), cookies);
     }
     @Override
     public List<Cookie> loadForRequest(HttpUrl url) {
      List<Cookie> cookies = cookieStore.get(url.host());
      return cookies != null ? cookies : new ArrayList<Cookie>();
     }
    }).build();

Summarize


Related articles: