Android OkHttp, refresh expired token

后端 未结 5 1138
我寻月下人不归
我寻月下人不归 2021-01-30 18:14

Scenario: I am using OkHttp / Retrofit to access a web service: multiple HTTP requests are sent out at the same time. At some point the auth token expires, and

5条回答
  •  孤城傲影
    2021-01-30 19:00

    If you wan't your threads to bock while the first one refresh the token you can use a synchronized block.

    private final static Object lock = new Object();
    private static long lastRefresh;
    
    ...
    synchronized(lock){ // lock all thread untill token is refreshed
       // only the first thread does the w refresh
       if(System.currentTimeMillis()-lastRefresh>600000){ 
          token = refreshToken();
          lastRefresh=System.currentTimeMillis();
       }
    }
    

    Here 600000 (10 min) is arbitrary this number should be big enouth to prevent muliple refresh call and smaller than your token expiration time so that you call the refresh when the token expires.

提交回复
热议问题