可以将 OkHttpClient 对象设置为单例模式,这样在整个应用程序中只有一个 OkHttpClient 对象,然后在工具类中提供一个公共方法,用于添加拦截器。

示例代码如下:

public class OkHttpUtil {

    private static OkHttpClient okHttpClient;

    private OkHttpUtil() {}

    public static synchronized OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient.Builder()
                    .connectionPool(new ConnectionPool()) // 启用连接池
                    .build();
        }
        return okHttpClient;
    }

    public static void addInterceptor(Interceptor interceptor) {
        getOkHttpClient().newBuilder().addInterceptor(interceptor).build();
    }

}

在使用时,可以先调用 addInterceptor 方法添加拦截器,然后再发起请求。

示例代码如下:

OkHttpUtil.addInterceptor(new LoggingInterceptor()); // 添加拦截器

Request request = new Request.Builder()
        .url('http://www.example.com')
        .build();

OkHttpClient okHttpClient = OkHttpUtil.getOkHttpClient();
Response response = okHttpClient.newCall(request).execute();
Android OkHttp 工具类:连接池、拦截器及单例模式

原文地址: https://www.cveoy.top/t/topic/owis 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录