Android使用Retrofit增加Interceptor拦截器报错UnsupportedOperationException报错解决

2024-02-01 546点热度 0人点赞 0条评论

开发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();
}

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论