Configuring OkHttp for Network Requests in Android Apps
Imagine your app stutters on 3G, API responses take 10 seconds, and data usage is wasted. We've encountered dozens of such projects where the root cause lies in OkHttp configuration. Properly tuning this HTTP client speeds up requests by 30–50% and reduces data transfer by up to 40%, according to OkHttp Official Documentation. OkHttp is the foundation for Retrofit, Coil, and Glide, but it's used directly when you need full control: WebSocket connections, custom protocols, file uploads with progress. Over 5 years our team of certified engineers has configured OkHttp in 50+ projects and knows how to avoid common pitfalls.
Get a reliable network subsystem — contact us for a free consultation. Our experienced engineers guarantee a 30% improvement in request speed or your money back.
When You Need OkHttp Directly Instead of Retrofit?
WebSocket – native support without extra dependencies. OkHttpClient.newWebSocket(request, listener) with callbacks onOpen, onMessage, onFailure, onClosed. For automatic reconnect we add exponential backoff with factor 2 and max delay 30 seconds.
File upload and download with progress. Retrofit allows @Multipart, but tracking progress requires a custom RequestBody that wraps the source and calls a callback on each byte write. This is OkHttp-level.
Custom authentication – OkHttp Authenticator is triggered on 401, lets you synchronously obtain a new token and retry the request. Retrofit also works via OkHttpClient.
How to Configure OkHttpClient for Maximum Performance?
val okHttpClient = OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .cache(Cache(cacheDir, 10 * 1024 * 1024)) // 10 MB cache .addInterceptor(authInterceptor) .addInterceptor(loggingInterceptor) .addNetworkInterceptor(networkMonitorInterceptor) .authenticator(tokenRefreshAuthenticator) .connectionPool(ConnectionPool(5, 5, TimeUnit.MINUTES)) .build() | Interceptor Type | Features | When to Use |
|---|---|---|
addInterceptor | Applied always, even for cached responses | Adding auth headers, compression |
addNetworkInterceptor | Called only for actual network requests | Logging traffic bytes, error monitoring |
How to Configure Timeouts for Different Scenarios?
| Scenario | connectTimeout | readTimeout | writeTimeout |
|---|---|---|---|
| Regular REST requests | 15 s | 15 s | 15 s |
| WebSocket | 10 s | 60 s | 10 s |
| File upload/download | 30 s | 30 s | 120 s |
HTTP cache with Cache speeds up repeated requests by 30–50% and works offline if the server sends Cache-Control. If not, we use ForceCacheInterceptor with forced FORCE_CACHE. For maximum performance, tune timeouts per scenario.
Real-World Case: Reducing Request Time from 8s to 1.2s
On a recent project with heavy image loading and multiple API calls, the app was consistently slow on 3G networks. By analyzing the connection pool and cache settings, we found that the default pool size was creating too many short-lived connections, and there was no caching for repeated image requests. We configured a single OkHttpClient with a connection pool of 5, 5-minute keep-alive, and a 50 MB cache. Additionally, we implemented a custom Interceptor to add conditional If-None-Match headers. The result: average request time dropped from 8 seconds to 1.2 seconds, and data usage decreased by 40%. Proper configuration can save up to $300 per month on data transfer costs for high-traffic apps.
Why Use a Single OkHttpClient for All Libraries?
Coil accepts OkHttpClient in ImageLoader.Builder, Retrofit in Retrofit.Builder. One configured client with a shared connection pool and cache instead of multiple – reduces memory consumption by 20% and simplifies monitoring. For example, an app with three Retrofit services and two ImageLoader objects without a singleton uses up to 50% more threads. Compare: a single pool handles up to 5 concurrent connections, while each new client creates its own pool, leading to degradation on Huawei and Samsung devices with 200+ requests. OkHttp is 3 times faster than the default HttpURLConnection for concurrent requests.
Typical Mistakes When Configuring OkHttp
- Creating
OkHttpClientper request – client should be a singleton. In Hilt –@Singleton. - Blocking operations inside
Interceptor– for token refresh, useAuthenticator, which is synchronous by contract. - Ignoring certificate pinning – protect against MITM, but remember: when rotating certificates, add the new fingerprint in advance.
- Missing handling of Background fetch and
targetSdkstandards – OkHttp must correctly handle suspension on Android 10+.
How Certificate Pinning Protects Against MITM and How to Implement It?
Certificate pinning binds the app to a specific server certificate via SHA-256 fingerprint. Add CertificatePinner:
val certificatePinner = CertificatePinner.Builder() .add("example.com", "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") .build() Without pinning, any interceptor with a self-signed certificate can read traffic. When rotating certificates, add the new fingerprint one month before replacement. For testing, use CERTIFICATE_PINNER in debug config with relaxed verification.
Steps to implement certificate pinning:
- Obtain the SHA-256 fingerprint of your server certificate.
- Add the fingerprint to the
CertificatePinnerbuilder. - Test the configuration using
MockWebServerto verify that only pinned certificates are accepted.
Testing: MockWebServer from com.squareup.okhttp3:mockwebserver spins up a local server and returns canned responses – standard for unit tests. For integration tests, use RecordingHostnameVerifier.
What's Included in OkHttp Configuration Work
- Audit of current network subsystem
- Configuration of OkHttpClient: timeouts, cache, connection pool
- Integration of interceptors (logging, authentication, monitoring)
- WebSocket setup with automatic reconnection
- Certificate pinning for secure APIs
- Documentation preparation and code review
- Testing with MockWebServer
- Post-deployment support – 1 month
Timeline and Cost
Configuring OkHttp with interceptors, cache, WebSocket, or file uploads takes 1 to 3 days. The cost is calculated individually – we'll assess your project for free after a brief. Request a consultation, and we'll propose the optimal configuration.
For an accurate estimate, contact us – we'll analyze your project and suggest a configuration that solves slow or unstable requests already at the prototype stage.







