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

59

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

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)

当我尝试添加一个新的拦截器时,它会报错,提示它不是可修改的集合。但是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).
   */

我做错了什么?可能是个bug吗?


你正在使用哪个版本的OkHttp? - Blackbelt
@Usmankhan,你试过我的解决方案了吗? - Konrad Krakowiak
抱歉之前没有更新,但是是的,我已经按照你的建议修改了我的代码。结果非常完美,一切都运行得很顺利。 - Usman khan
3个回答

139

当您将 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();

这应该能解决你的问题。


他们默认使用的是okhttp3吗? - Blackbelt
你是指Retrofit 2.0-beta3吗?如果是的话,答案是肯定的。据我所知,在beta3中不再有com.squareup.okhttp.OkHttpClient。我昨天也遇到了同样的问题;) - Konrad Krakowiak
3
com.squareup.okhttp.OkHttpClientokhttp3.OkHttpClient 替代。 - Konrad Krakowiak
在哪里定义token] - Muhammad Younas
你是指认证令牌吗?你可以添加新的拦截器,在拦截方法中添加头部,或者将头部作为客户端方法的第一个参数传递,但更好的方法是使用拦截器。 - Konrad Krakowiak
显示剩余9条评论

5

如果其他答案不起作用,请尝试以下方法:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接