0

I know that using a single instance of OkHttpClient for the entire app is a best practice. But I came across with TrustKit and I needed to implement the next code:

OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
URL url = new URL("https://www.url.com");
String serverHostname = url.getHost();
builder.sslSocketFactory(TrustKit.getInstance().getSSLSocketFactory(serverHostname),
TrustKit.getInstance().getTrustManager(serverHostname)).build();

Then I realized that maybe the right way is to have a single instance per domain. Currently I have to implement cert pinning and I have inside my application multiple domains where I fetch the information my app needs.

So the question is: what is the best practice in case you have multiple domains when you try to instantiate a OkHttpClient? One instance per domain?

Leandro Ocampo
  • 1,894
  • 18
  • 38
  • 1
    Your specific "one instance per domain" restriction is coming from your use of TrustKit-Android. Not all developers use that, and so its restrictions would not apply to people using OkHttp3 on its own for certificate pinning or in conjunction with other libraries (e.g., my CWAC-NetSecurity). In the specific scenario of using TrustKit-Android, one `OkHttpClient` per domain may be required. Otherwise, AFAIK, the standard is one `OkHttpClient` per process, unless there are other limiting factors. – CommonsWare Aug 23 '17 at 19:33
  • You are right, this restriction is coming from TrustKit-Android. So that is the reason I wanted to know if I hadn't had that restriction I would have needed to implement one instance for each domain or keep using one single instance. Do you know where I can get that information about "one OkHttpClient per process" @CommonsWare ? – Leandro Ocampo Aug 23 '17 at 19:42
  • 1
    Well, using lots of `OkHttpClient` instances, without care, can run into problems, as [this developer discovered](https://stackoverflow.com/a/42949077/115145). Typically, you want to maximize the sharing of the threads and connections and stuff, and so having one per process achieves that. If you have several `OkHttpClient` instances, you would want to have them share a `ConnectionPool` and stuff, as outlined in that answer. – CommonsWare Aug 24 '17 at 00:27
  • You can also get this by starting with a root OkHttpClient instance, and for each additional host hostClient = rootClient.newBuilder().xxx.build() – Yuri Schimke Aug 24 '17 at 05:34

1 Answers1

0

As CommonsWare said,

Your specific "one instance per domain" restriction is coming from your use of TrustKit-Android.

If you don't need to make particular tasks for each domain, then it is better to have a single OkHttpClient instance. Otherwise apply this solution where a common ConnectionPool is created for each client.

I ended up using cert pinning with okhttp3, so I do not have code to share that implements the last solution sadly.

Leandro Ocampo
  • 1,894
  • 18
  • 38