升级到OkHttp3后,OkHttpClient抛出异常

时间:2016-01-24 07:57:15

标签: android retrofit okhttp retrofit2 okhttp3

我正在使用以下代码行为我使用Retrofit2发送的所有请求添加默认标头:

private static OkHttpClient defaultHttpClient = new OkHttpClient();
static {
    defaultHttpClient.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request().newBuilder()
                    .addHeader("Accept", "Application/JSON").build();
            return chain.proceed(request);
        }
    });
}

升级到beta-3版本后,我不得不将OkHttp升级到OkHttp3(实际上我只是将包名称从okhttp更改为okhttp3,该库包含在改造中)。之后我从这一行得到例外:

defaultHttpClient.networkInterceptors().add(new Interceptor());
  

引起:java.lang.UnsupportedOperationException                                                                     在java.util.Collections $ UnmodifiableCollection.add(Collections.java:932)

  

引起:java.lang.ExceptionInInitializerError

这里有什么问题?

3 个答案:

答案 0 :(得分:66)

如果要创建OkHttp(3)客户端对象,则必须使用构建器。

尝试更改此内容:

private static OkHttpClient defaultHttpClient = new OkHttpClient();

对于这样的事情:

  OkHttpClient defaultHttpClient = new OkHttpClient.Builder()
       .addInterceptor(
           new Interceptor() {
             @Override
             public Response intercept(Interceptor.Chain chain) throws IOException {
                   Request request = chain.request().newBuilder()
                   .addHeader("Accept", "Application/JSON").build();
               return chain.proceed(request);
              }
           }).build();

答案 1 :(得分:1)

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile "com.squareup.retrofit2:converter-gson:2.1.0"
compile "com.squareup.retrofit2:adapter-rxjava:2.1.0"
compile 'com.squareup.okhttp3:logging-interceptor:3.4.0'

你应该使用这些版本。只需添加它们,同步您的gradle ,删除所有导入,然后重试。

import okhttp3.Interceptor;

import okhttp3.OkHttpClient;

import okhttp3.Request;

import okhttp3.Response;

import okhttp3.logging.HttpLoggingInterceptor;

import retrofit2.Retrofit;

import retrofit2.converter.gson.GsonConverterFactory;

答案 2 :(得分:0)

要添加V.Sch的答案,可以使用Java Lambda将其缩短为

    OkHttpClient httpClient = new OkHttpClient.Builder()
        .addInterceptor(
                chain -> {
                    Request request = chain.request().newBuilder()
                            .addHeader("Accept", "Application/JSON").build();
                    return chain.proceed(request);
                }).build();