Android — OkHttpClient如何使用 ?

JLin
1 min readMay 16, 2019

--

主要談不是說如何宣告,如何呼叫,而是因為我們在一個App內的request其實非常多,我們該不該把OkHttpClient宣告程single ?或者透過Dagger方式注射?

我想主要是可以看官方說明

有一句很重要的話

OkHttpClients should be shared

解釋說到

OkHttp performs best when you create a single OkHttpClient instance and reuse it for all of your HTTP calls. This is because each client holds its own connection pool and thread pools. Reusing connections and threads reduces latency and saves memory. Conversely, creating a client for each request wastes resources on idle pools. Use new OkHttpClient() to create a shared instance with the default settings:

其實同一個okHttpClient他們會共用pool,所以共用也會節省memory或者connection,不會瘋狂的create

或者你透過Builder也可以讓他自己有效個管理

// The singleton HTTP client.
public final OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor())
.cache(new Cache(cacheDir, cacheSize))
.build();

--

--

JLin

台中 / JAVA / Android /Kotlin / Kotlin Native 對於Kotlin衍生的JVM等技術 Compose for web / desktop / Ktor Server,生成式AI (Gemini/OpenAI)各式應用, 都有小興趣