Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Okhttp newBuilder per request

Tags:

java

okhttp

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()

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

  2. Classes calling makeRestCall decide 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.

like image 593
Phuthib Avatar asked Oct 22 '25 03:10

Phuthib


1 Answers

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

No, the original is unchanged. Its configuration is immutable.

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

Absolutely. That operation is cheap because it only duplicates the configuration. Resource-intensive stuff like the connection pool and cache are not duplicated.

like image 50
Jesse Wilson Avatar answered Oct 24 '25 18:10

Jesse Wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!