Okhttp newBuilder 每个请求

Okhttp newBuilder per request

正在尝试以正确的方式实施 okhttp。我知道 OkHttpClient 必须共享(Singleton),但是我不是很清楚 .newBuilder();

示例代码:

// Instantiated once
private static OkHttpClient client = new OkHttpClient.Builder()
        .readTimeout(readTime, TimeUnit.MILLISECONDS)
        .connectionPool(new ConnectionPool(200, connectTimeout, TimeUnit.MILLISECONDS));
        .build(); 

public static String makeRestCall(String url, String data, Interceptor customInterceptor) {
    // Questions on the line below
    OkHttpClient newClient = client.newBuilder()
        .addInterceptor(customInterceptor)
        .build();

    ....
    try (Response response = newClient.newCall(httpRequest).execute()) {
            final ResponseBody body = response.body();
            return body.string();
    }
    return "NO_DATA";
}
 

我有一些关于.newBuilder()

的问题
  1. 当我们向 newClient 添加新的拦截器时,原始 client 是否也会通过引用更新?

  2. 类 调用 makeRestCall 决定他们需要什么 customInteceptor。可以为每个请求调用 .newBuilder() 吗?

我一直在搜索文档并尝试实现,但对上述内容还不是很清楚。

感谢任何assistance/pointers。

  1. When we add a new interceptor to newClient, does the original client also get updated by reference?

没有,原来没变。它的配置是不可变的。

  1. Classes calling makeRestCall decide on what customInteceptor they need. Is it ok to call .newBuilder() for every request?

当然可以。该操作很便宜,因为它只复制配置。 Resource-intensive 连接池和缓存之类的东西没有重复。