2015-04-05 115 views
7

根據OKHttp文檔,我使用OkHttp 2.3以及基本身份驗證請求,它會自動重試未經身份驗證的請求,但每當我提供無效憑據時,請求會花費太多時間,最後我會得到此異常:在Okhttp中處理身份驗證

java.net.ProtocolException:太多的後續請求:21

如何防止OkHttp從自動重試身份認證的請求,並返回401 Unauthorized呢?

回答

9
protected Authenticator getBasicAuth(final String username, final String password) { 
    return new Authenticator() { 
     private int mCounter = 0; 

     @Override 
     public Request authenticate(Proxy proxy, Response response) throws IOException { 
      if (mCounter++ > 0) { 
       throw new AuthenticationException(
         AuthenticationException.Type.INVALID_LOGIN, response.message()); 
      } 

      String credential = Credentials.basic(username, password); 
      return response.request().newBuilder().header("Authorization", credential).build(); 
     } 

     @Override 
     public Request authenticateProxy(Proxy proxy, Response response) throws IOException { 
      return null; 
     } 
    }; 
} 

在我的身份驗證器中,我簡單地計算了嘗試 - 在X嘗試後,我拋出一個異常。

+0

非常感謝,這就是我最終做的事情,沒有什麼可以禁用Okhttp迄今爲止發現的多個試驗。 – 2015-04-17 13:42:33

1

修改Traxdata的回答版本的作品:

protected Authenticator getBasicAuth(final String username, final String password) { 
    return new Authenticator() { 
     private int mCounter = 0; 

     @Override 
     public Request authenticate(Route route, Response response) throws IOException { 
      Log.d("OkHttp", "authenticate(Route route, Response response) | mCounter = " + mCounter); 
      if (mCounter++ > 0) { 
       Log.d("OkHttp", "authenticate(Route route, Response response) | I'll return null"); 
       return null; 
      } else { 
       Log.d("OkHttp", "authenticate(Route route, Response response) | This is first time, I'll try to authenticate"); 
       String credential = Credentials.basic(username, password); 
       return response.request().newBuilder().header("Authorization", credential).build(); 
      } 
     } 
    }; 
} 

然後,你需要:

OkHttpClient.Builder builder = new OkHttpClient.Builder(); 
builder.authenticator(getBasicAuth("username", "pass")); 
retrofit = new Retrofit.Builder() 
      .baseUrl(BASE_URL) 
      .client(builder.build()) 
      .addConverterFactory(GsonConverterFactory.create()) 
      .build(); 

就是這樣。