2016-01-08 4 views
47

J'essaye d'ajouter l'authentification basée sur le jeton via Retrofit 2.0-beta3 et OkHttpClient dans Android en utilisant des intercepteurs. Mais je reçois UnsupportedOperationException quand j'ajoute mon intercepteur dans OkHttpClient. Voici mon code: En ApiClient.javaOpération non prise en charge: Android, Retrofit, OkHttp. Ajouter un intercepteur dans OkHttpClient

public static TrequantApiInterface getClient(final String token) { 
     if(sTreqantApiInterface == null) { 

      Log.v(RETROFIT_LOG, "Creating api client for the first time"); 
      OkHttpClient okClient = new OkHttpClient(); 

      okClient.interceptors().add(new Interceptor() { 
       @Override 
       public Response intercept(Interceptor.Chain chain) throws IOException { 
        Request original = chain.request(); 

        // Request customization: add request headers 
        Request.Builder requestBuilder = original.newBuilder() 
          .header("Authorization", token) 
          .method(original.method(), original.body()); 

        Request request = requestBuilder.build(); 
        return chain.proceed(request); 
       } 
      }); 

      Retrofit client = new Retrofit.Builder() 
        .baseUrl(baseUrl) 
        .client(okClient) 
        .addConverterFactory(GsonConverterFactory.create()) 
        .build(); 
      sTreqantApiInterface = client.create(TrequantApiInterface.class); 
     } 
     return sTreqantApiInterface; 
    } 

et je l'utilise comme:

private void ampFreqTest(){ 
    String token = getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE) 
         .getString(getString(R.string.key_token), ""); 

    service = ApiClient.getClient(token); 
    //I get an exception on this line: 
    Call<List<AmpFreq>> call = service.getUserAmpFreq("1"); 
    call.enqueue(new Callback<List<AmpFreq>>() { 
     @Override 
     public void onResponse(Response<List<AmpFreq>> response) { 
      Toast.makeText(HomeScreen.this, "Got result", Toast.LENGTH_LONG); 

      Log.v(ApiClient.RETROFIT_LOG, "Success api client." + response.message()); 
      Log.v(ApiClient.RETROFIT_LOG, "Success api client."); 
     } 
     @Override 
     public void onFailure(Throwable t) { 
      Toast.makeText(HomeScreen.this, t.getMessage() , Toast.LENGTH_LONG); 
      Log.v(ApiClient.RETROFIT_LOG, "Fail api client." + t.getMessage()); 
     } 
    }); 
} 

Mais je reçois cette erreur:

Process: com.trequant.usman.trequant_android, PID: 14400 
java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableCollection.add(Collections.java:932) 
at com.trequant.usman.trequant_android.api.ApiClient.getClient(ApiClient.java:41) 

Il me donne l'erreur sur l'ajout un nouvel intercepteur disant qu'il n'est pas modifiableCollection mais la documentation de la fonction interceptors() dit:/**

* Returns a modifiable list of interceptors that observe the full span of each call: from before 
    * the connection is established (if any) until after the response source is selected (either the 
    * origin server, cache, or both). 
    */ 

Qu'est-ce que je fais mal? Serait-ce un bug?

+0

version de OkHttp utilisez-vous? – Blackbelt

+0

@Usmankhan Avez-vous essayé ma solution? –

+0

Désolé je n'ai pas mis à jour avant mais ouais, j'avais changé mon code à ce que vous aviez suggéré. Et ça a fonctionné comme un charme. –

Répondre

124

Ce problème se produit lorsque vous modifiez Retrofit 2.0-beta2 à Rénovation 2.0 beta3. Vous devez utiliser le constructeur si vous voulez créer l'objet OkHttpClient.

Change:

OkHttpClient okClient = new OkHttpClient(); 

okClient.interceptors().add(new Interceptor() { 
     @Override 
     public Response intercept(Interceptor.Chain chain) throws IOException { 
      Request original = chain.request(); 

      // Request customization: add request headers 
      Request.Builder requestBuilder = original.newBuilder() 
        .header("Authorization", token) 
        .method(original.method(), original.body()); 

      Request request = requestBuilder.build(); 
      return chain.proceed(request); 
     } 
}); 

à:

OkHttpClient okClient = new OkHttpClient.Builder() 
      .addInterceptor(
       new Interceptor() { 
       @Override 
       public Response intercept(Interceptor.Chain chain) throws IOException { 
         Request original = chain.request(); 

         // Request customization: add request headers 
         Request.Builder requestBuilder = original.newBuilder() 
           .header("Authorization", token) 
           .method(original.method(), original.body()); 

         Request request = requestBuilder.build(); 
         return chain.proceed(request); 
        } 
       }) 
      .build(); 

Il devrait résoudre votre problème.

+0

utilisent-ils okhttp3 par défaut? – Blackbelt

+0

Voulez-vous dire Retrofit 2.0-beta3? Si oui, la réponse est oui. Pour autant que je sache, il n'y a plus de 'com.squareup.okhttp.OkHttpClient' en beta3. J'ai eu le même problème hier;) –

+0

s'il n'y a pas de 'OkHttpClient' comment l'instanciez-vous? – Blackbelt

-2

Essayez ceci si l'autre réponse ne fonctionne pas:

OkHttpClient okHttpClient = new OkHttpClient.Builder() 
    .addInterceptor(new MyInterceptor()) 
    .build(); 
retrofit = new Retrofit.Builder() 
    .baseUrl("http://google.com") 
    .addConverterFactory(GsonConverterFactory.create()) 
    .client(okHttpClient) 
    .build();