升级到OkHttp3后,OkHttpClient抛出异常

Ash*_*lak 31 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);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

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

defaultHttpClient.networkInterceptors().add(new Interceptor());
Run Code Online (Sandbox Code Playgroud)

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


引起:java.lang.ExceptionInInitializerError


这里有什么问题?

V.S*_*Sch 68

如果要创建OkHttp(3)Client对象,则必须使用构建器.

尝试改变这个:

private static OkHttpClient defaultHttpClient = new OkHttpClient();
Run Code Online (Sandbox Code Playgroud)

对于这样的事情:

  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();
Run Code Online (Sandbox Code Playgroud)