Okhttp newBuilder每个请求



尝试正确实现okhttp。我理解OkHttpClient必须共享(单例),但我不清楚理解.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的类决定它们需要什么样的custominterceptor。是否可以为每个请求调用.newBuilder()?

我一直在搜索文档并尝试实现,但上面的内容还不清楚。

任何帮助/指示都是感激的。

  1. 当我们向newClient添加一个新的拦截器时,原始客户端是否也通过引用得到更新?

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

  1. 调用makeRestCall的类决定它们需要什么custominterceptor。是否可以为每个请求调用。newbuilder () ?

绝对。这个操作很便宜,因为它只复制配置。资源密集型的东西,如连接池和缓存是不重复的。

最新更新