2016-12-01 29 views
-2

爲什麼慣於此編譯:「OkHttpClient不能轉換爲MyOkHttpClient」

MyOkHttpClient okClient = new MyOkHttpClient.Builder() 
       .addInterceptor(new AddCookiesInterceptor()) 
       .addInterceptor(new ReceivedCookiesInterceptor()).build(); 

不兼容的類型。 要求: my.path.util.auth.MyOkHttpClient 發現: okhttp3.OkHttpClient

這是我的課:

public class MyOkHttpClient extends okhttp3.OkHttpClient implements Authenticator { 

    private static int MAX_AUTHENTICATE_TRIES = 3; 



    @Override 
    public Request authenticate(Route route, Response response) throws IOException { 
     if (responseCount(response) >= MAX_AUTHENTICATE_TRIES) { 
      return null; // If we've failed 3 times, give up. - in real life, never give up!! 
     } 
     String credential = Credentials.basic(AUTHTOKEN_USERNAME, AUTHTOKEN_PASSWORD); 
     return response.request().newBuilder().header("Authorization", credential).build(); 
    } 

    private int responseCount(Response response) { 
     int result = 1; 
     while ((response = response.priorResponse()) != null) { 
      result++; 
     } 
     return result; 
    } 


} 
+1

您不僅延長了外部類。您沒有擴展Builder。順便說一下,你試圖在這裏完成什麼?根本沒有任何理由讓你擴展OkHttpClient。 – rmlan

+0

我無法擴展OkthhpClient.Builder ....是否有另一種解決方法? – Mike6679

+0

是的。不要這樣做。實現Builder模式的東西通常很難擴展,因爲它們並不是真正意義上的。 – rmlan

回答

0

根據您的意見,您錯誤地認爲你是裝飾用OkHttpClient定製認證邏輯。

相反,您不必要地擴展OkHttpClient 實現Authenticator接口。您可以簡單地使用任何您想要的自定義身份驗證器來構建標準的OkHttpClient。

因此,更像是你真正想要

public class MyAuthenticator implements Authenticator { 

    private static int MAX_AUTHENTICATE_TRIES = 3; 

    @Override 
    public Request authenticate(Route route, Response response) throws IOException { 
     if (responseCount(response) >= MAX_AUTHENTICATE_TRIES) { 
      return null; // If we've failed 3 times, give up. - in real life, never give up!! 
     } 
     String credential = Credentials.basic(AUTHTOKEN_USERNAME, AUTHTOKEN_PASSWORD); 
     return response.request().newBuilder().header("Authorization", credential).build(); 
    } 

    private int responseCount(Response response) { 
     int result = 1; 
     while ((response = response.priorResponse()) != null) { 
      result++; 
     } 
     return result; 
    } 


} 

然後當你建立你的客戶

OkHttpClient okClient = new OkHttpClient.Builder() 
      .addInterceptor(new AddCookiesInterceptor()) 
      .addInterceptor(new ReceivedCookiesInterceptor()) 
      .authenticator(new MyAuthenticator()) 
      .build(); 
相關問題