2017-07-31 51 views
0

我是新來的android編程和改造,我做了一個示例應用程序,我必須使用訪問令牌進行兩個並行網絡調用。 當訪問令牌過期並返回401狀態碼時,如果我看到401 HTTP狀態碼,我必須使用此訪問令牌進行刷新刷新調用,但是並行調用的問題是它導致刷新競爭條件刷新令牌是否有避免這種情況的最佳方法,以及如何智能地刷新令牌而沒有任何衝突。當響應未授權重試最後一次失敗的請求與他們處理背景刷新令牌調用改進並行網絡調用

回答

2

OkHttp會自動詢問憑據身份驗證

public class TokenAuthenticator implements Authenticator { 
    @Override 
    public Request authenticate(Proxy proxy, Response response) throws IOException { 
     // Refresh your access_token using a synchronous api request 
     newAccessToken = service.refreshToken(); 

     // Add new header to rejected request and retry it 
     return response.request().newBuilder() 
      .header(AUTHORIZATION, newAccessToken) 
      .build(); 
    } 

    @Override 
    public Request authenticateProxy(Proxy proxy, Response response) throws IOException { 
     // Null indicates no attempt to authenticate. 
     return null; 
    } 

連接的驗證器OkHttpClient你做攔截

OkHttpClient okHttpClient = new OkHttpClient(); 
okHttpClient.setAuthenticator(authAuthenticator); 

使用此客戶端創建改造RestAdapter時

RestAdapter restAdapter = new RestAdapter.Builder() 
      .setEndpoint(ENDPOINT) 
      .setClient(new OkClient(okHttpClient)) 
      .build(); 
return restAdapter.create(API.class); 

選中此相同的方式:Fore more details visit this link

0

嘗試撥打隊列,如刷新令牌操作:

class TokenProcessor { 
    private List<Listener> queue = new List<Listener>(); 
    private final Object synch = new Object(); 
    private State state = State.None; 
    private String token; 
    private long tokenExpirationDate; 

    public void getNewToken(Listener listener){ 
     synchronized(synch) { 

      // check token expiration date 
      if (isTokenValid()){ 
       listener.onSuccess(token); 
       return; 
      } 
      queue.add(listener); 

      if (state != State.Working) { 
       sendRefreshTokenRequest(); 
      } 
     } 
    } 
    private void sendRefreshTokenRequest(){ 
     // get token from your API using Retrofit 
     // on the response call onRefreshTokenLoaded() method with the token and expiration date 
    } 
    private void onRefreshTokenLoaded(String token, long expirationDate){ 
     synchronized(synch){ 
      this.token = token; 
      this.tokenExpirationDate = expirationDate; 

      for(Listener listener : queue){ 
       try { 
        listener.onTokenRefreshed(token); 
       } catch (Throwable){} 
      } 
      queue.clear();     
     } 
    } 
} 

這是一個示例代碼,它是如何實現的。