Mobile Development 15 min read

How to Seamlessly Replace OkHttp with Cronet on Android

This article details the motivation, architecture, and step‑by‑step integration of Google’s Cronet network library into NetEase Cloud Music’s Android client, covering adaptation layers, interceptor handling, timeout support, compatibility fixes, performance gains, and future QUIC enhancements.

NetEase Cloud Music Tech Team
NetEase Cloud Music Tech Team
NetEase Cloud Music Tech Team
How to Seamlessly Replace OkHttp with Cronet on Android

Background

NetEase Cloud Music runs on many platforms (iOS, Android, PC, MAC, IoT). The mobile side, being the earliest and largest user base, accumulated stable network policies, but inconsistencies existed across platforms. To unify network capabilities and reduce duplicated effort, the team chose Google Chromium’s Cronet library, which offers proven stability and QUIC support. Android was the first target and has been in production for over a year.

Introducing Cronet

Cronet is the network component of Chromium that can be compiled as a standalone library for Android and iOS. It powers high‑traffic apps such as YouTube and the Google suite. Key features include:

Support for HTTP/2, QUIC, and WebSocket

Request priority tagging

Memory and disk caching

Brotli compression (≈20% better than gzip at the same quality)

Integration Options

The existing codebase uses OkHttp. Cronet’s API is not compatible with OkHttp, so two strategies were considered:

Refactor the business‑level network API to use Cronet directly, replacing the old OkHttp‑based interfaces.

Keep the business layer unchanged and insert a glue layer that swaps the underlying implementation to Cronet while preserving the OkHttp interceptor chain.

Option 1 would require re‑implementing many OkHttp features (interceptors, cookie store, cache, event listeners), incurring huge cost. Option 2 creates a CronetInterceptor placed at the end of the OkHttp interceptor chain, allowing existing interceptors to run unchanged while routing the actual request through Cronet. The team adopted Option 2.

Overall Android Network Architecture

The architecture is divided into four layers from bottom to top:

Protocol Layer

Extracted directly from Chromium, this layer implements core protocols and internal optimizations of Cronet. It is rarely modified.

Common Capability Layer

Contains network policies and components (e.g., APM, HttpDns) that were originally written in Java but have been moved to C++ for reuse across platforms.

Adaptation Layer

Acts as the glue that maps OkHttp calls to Cronet without requiring changes in the upper business code.

Business Support Layer

Provides the features needed by the app’s business logic and remains untouched.

Adaptation Details

OkHttp Interface Adaptation

Interceptor adaptation : The team recreated the core logic of three built‑in OkHttp interceptors ( RetryAndFollowUpInterceptor, BridgeInterceptor, CacheInterceptor) inside CronetInterceptor so that cookie, cache, and authentication behavior stay the same.

EventListener adaptation : Since Cronet provides its own callbacks, only a subset of OkHttp’s EventListener functionality was bridged. Full replication was deemed unnecessary.

Timeout adaptation : Cronet lacks direct timeout APIs, so the team added SetConnectTimeoutDuration and SetReadTimeoutDuration methods in the native layer and exposed them to Java via JNI.

void CronetURLRequest::SetConnectTimeoutDuration(uint32_t connect_timeout_ms);
void CronetURLRequest::SetReadTimeoutDuration(uint32_t read_timeout_ms);

Network Request Adaptation

Requests are converted between OkHttp and Cronet formats, and a diagram (omitted) illustrates the flow. Java‑side policies that were previously implemented in Java are now routed through C++ plugins via a JSON‑based bridge (named CppBridge) to keep future updates decoupled.

Problem Solving

Thread Optimization

Cronet’s CronetHttpURLConnection can run on the current thread using MessageLoop, avoiding extra thread switches that would occur if a separate executor were supplied.

Compatibility Issues

Cronet limits concurrent HTTP connections to six; exceeding this can block further requests.

Requests without a Content‑Type header trigger an IllegalArgumentException.

Cronet throws exceptions for 4xx responses, whereas OkHttp returns the status code for the caller to handle.

Redirect Handling

OkHttp updates the Host header on redirects; Cronet does not by default. The team added a native method to set redirect headers and modified the Java callback to update the Host before following the redirect.

void CronetURLRequest::NetworkTasks::SetRedirectHeader(const std::string& key, const std::string& value);
@Override
protected void handleRedirectReceived(UrlRequest request, UrlResponseInfo info, String newLocationUrl) {
    Uri newUri = Uri.parse(newLocationUrl);
    String host = newUri.getHost();
    request.setRedirectHeader("Host", host);
    request.followRedirect();
}

Gray Release & Monitoring

Because the network library touches many parts of the app, a careful rollout plan was followed:

Switch to Cronet in development environments early to surface issues.

Perform staged gray releases, monitoring stability platforms and user feedback.

Implement automatic fallback to OkHttp after a configurable number of failures, and log detailed metrics for analysis.

After full rollout, extend observation periods, compare latency, error rates, tail‑latency, and business‑level KPIs.

Results after a year of production use show a 16% reduction in main‑API request latency and a 4% drop in error rate.

Future Plans

The team is extending Cronet’s NQE module for weak‑network detection and notification. They also plan to leverage QUIC (HTTP/3) features such as reduced connection RTT, connection migration via CID, head‑of‑line blocking elimination, user‑space congestion control, and improved security. Initial QUIC trials have shown promising performance, and further server‑side changes are being tracked.

PerformanceAndroidCronetQUICOkHttpNetwork Library
NetEase Cloud Music Tech Team
Written by

NetEase Cloud Music Tech Team

Official account of NetEase Cloud Music Tech Team

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.