Trying to implement okhttp the correct way. I understand the OkHttpClient must be shared (Singleton), however I am not clearly understanding .newBuilder();
Sample Code:
// 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";
}
I have a few questions around .newBuilder()
When we add a new interceptor to
newClient, does the originalclientalso get updated by reference?Classes calling
makeRestCalldecide on what customInteceptor they need. Is it ok to call.newBuilder()for every request?
I have been searching the documentation and playing with the implementation but haven't had clarity on the above.
Any assistance/pointers are appreciated.