2016-01-08 18 views
47

インターセプタを使用してAndroidでRetrofit 2.0-beta3とOkHttpClient経由でトークンベースの認証を追加しようとしています。しかし、私の傍受者をOkHttpClientに追加するとUnsupportedOperationExceptionが発生します。ここ は私のコードです:ApiClient.javaサポートされていない操作:Android、Retrofit、OkHttp。 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; 
    } 

そして、私は次のようにそれを使用する:

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()); 
     } 
    }); 
} 

しかし、私はこのエラーを取得する:

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) 

それは私の追加に関するエラーが発生しますmodifiableCollectionではないが、interceptors()関数のドキュメントによると、新しいインターセプタは:/ **

* 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). 
    */ 

私は間違っていますか?それはバグでしょうか?

+0

OkHttpのどのバージョンを使用していますか? – Blackbelt

+0

@ Usmankhan私の解決策を試しましたか? –

+0

申し訳ありませんが、私は前にそれを更新していませんでしたが、ええ、あなたの提案をあなたの提案に変更しました。そしてそれは魅力のように働いた。 –

答えて

124

あなたは2.0ベータ3レトロフィットレトロフィット2.0ベータ2を変更すると、この問題が発生します。 OkHttpClientオブジェクトを作成する場合は、Builderを使用する必要があります。

変更:

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(); 

それはあなたの問題を解決する必要があります。他の答えは動作しない場合

+0

はデフォルトでokhttp3を使用していますか? – Blackbelt

+0

Retrofit 2.0-beta3を意味しますか?はいの場合 - 答えは「はい」です。私が知る限り、beta3にはもうcom.squareup.okhttp.OkHttpClientは存在しません。私は昨日同じ問題を抱えていました;) –

+0

'OkHttpClient'がない場合、どうやってそれをインスタンス化しますか? – Blackbelt

-2

はこれを試してみてください:

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