不支持的操作:Android,Retrofit,OkHttp。在OkHttpClient中添加拦截器

时间:2016-01-08 10:31:51

标签: java android retrofit okhttp retrofit2

我正在尝试使用拦截器通过Android中的Retrofit 2.0-beta3和OkHttpClient添加基于令牌的身份验证。但是当我在OkHttpClient中添加拦截器时,我得到UnsupportedOperationException。 这是我的代码: 在ApiClient.java中

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)

但是我收到了这个错误:

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

它给我添加一个新拦截器的错误,说它不是modifiableCollection,但拦截器()函数的文档说:/ **

procedure Tform1.webvConsoleMessage(Sender: TObject; const browser: ICefBrowser; const message,
  source: ustring; line: Integer; out Result: Boolean);
begin
end;

我做错了什么?它可能是一个错误吗?

3 个答案:

答案 0 :(得分:130)

Retrofit 2.0-beta2 更改为 Retrofit 2.0-beta3 时,会出现此问题。如果要创建OkHttpClient对象,则必须使用构建器。

更改:

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

它可以解决您的问题。

答案 1 :(得分:1)

如果其他答案不起作用,请尝试此操作:

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

答案 2 :(得分:0)

您也可以通过这种方式添加。

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

 Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("ENDPOINT_URL")
            .addConverterFactory(GsonConverterFactory.create()).client(client)
            .build();