OkHttpClient throws an exception after upgrading to OkHttp3

I use the following lines of code to add a default header to all my requests sent using 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); } }); } 

After updating the version to beta-3, I also had to upgrade OkHttp to OkHttp3 (in fact, I just changed the package names from okhttp to okhttp3, the library is included in the modification). After that, I get exceptions from this line:

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

Called: java.lang.UnsupportedOperationException in java.util.Collections $ UnmodifiableCollection.add (Collections.java:932)




Called: java.lang.ExceptionInInitializerError




What is the problem?

+26
android retrofit retrofit2
Jan 24 '16 at 7:57
source share
3 answers

You need to use the builder if you want to create an OkHttp (3) client object.

Try changing this:

 private static OkHttpClient defaultHttpClient = new OkHttpClient(); 

Something like that:

  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(); 
+63
Jan 24 '16 at 9:03
source
 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' 

You should probably use these versions. Just put them in, synchronize gradle , delete all imports and try again.

 import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; 
+1
Sep 08 '16 at 15:16
source

To add B. Scha’s answer, with Java Lambda we can shorten this to

  OkHttpClient httpClient = new OkHttpClient.Builder() .addInterceptor( chain -> { Request request = chain.request().newBuilder() .addHeader("Accept", "Application/JSON").build(); return chain.proceed(request); }).build(); 
0
Apr 15 '19 at 6:57
source



All Articles