开发Android,使用Retrofit,想要增加一个拦截器,代码如下:
public static Retrofit initRetrofit() { OkHttpClient client = new OkHttpClient(); client.interceptors().add(chain -> { Request request = chain.request().newBuilder().addHeader("X-Token", "xxxxx").build(); return chain.proceed(request); }); return new Retrofit.Builder() .client(client) .baseUrl("http://1.2.3.4:8080/path/") .addConverterFactory(GsonConverterFactory.create()) .build(); }
报错:java.lang.UnsupportedOperationException
改成这样(OkHttpClient.Builder的方式):
public static Retrofit initRetrofit() { OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(chain -> { Request request = chain.request().newBuilder().addHeader("X-Token", "xxxxx").build(); Response response = chain.proceed(request); return response; }).build(); return new Retrofit.Builder() .client(client) .baseUrl("http://1.2.3.4:8080/path/") .addConverterFactory(GsonConverterFactory.create()) .build(); }
文章评论