Understand the OkHttp Interceptor
1. Detailed explanation of the interceptor interface
Interceptor
The interface is the basis of a custom interceptor, which only contains an abstract methodintercept
. The following is a detailed explanation of the parameters and return values of the method:
import ; import ; import ; import ; public class CustomInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { // chain contains all the information of the current request and the processing logic of subsequent interceptors Request originalRequest = (); // You can modify the original request, such as adding request headers, modifying the request method, etc. Request modifiedRequest = () .header("Custom-Header", "Custom-Value") .build(); // The procedure method will pass the modified request to the next interceptor and return the response Response response = (modifiedRequest); // Can process the response, such as adding custom response headers, parsing response bodies, etc. return () .header("Custom-Response-Header", "Custom-Response-Value") .build(); } }
Chain
Parameters:Chain
is an interface that represents the entire interceptor chain.()
Methods can obtain the current request object;
(request)
The method will pass the request to the next interceptor and return the response.
Response
Return value:intercept
The method must return aResponse
Object, this object can be the original response or a modified response.
2. Detailed execution process of interceptor chain
Overall process
The interceptor chain of OkHttp is an ordered set of interceptors, and the request and response pass through each interceptor in turn. The execution order of the interceptor chain is fixed, as follows:
1. User-defined interceptor (())
- Location: The front end of the interceptor chain.
- effect: This is an interceptor that developers can customize and add. Developers can implement some common business logic in this interceptor, such as unified addition of request headers, logging, request parameter encryption and other operations. Since it is at the front end of the interceptor chain, the original request can be processed the earliest, and the final response can be obtained, making it convenient for logging and other operations.
- Sample code:
import ; import ; import ; import ; public class CustomHeaderInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = (); Request newRequest = () .header("Custom-Header", "Custom-Value") .build(); return (newRequest); } }
2. Retry and redirect interceptor (RetryAndFollowUpInterceptor)
- Location: Following the user-defined interceptor.
- effect: Responsible for handling the retry and redirection logic of the request. When a network error occurs during the request process (such as connection timeout, DNS resolution failure, etc.), the interceptor will retry according to the configured retry policy; when the server returns a redirection response (such as 301 and 302 status codes), the redirection request will be automatically processed and a new request will be initiated to redirect the address.
-
Source code analysis:exist
intercept
In the method, the request will be processed continuously until the request is successful or the maximum number of retryes is reached. Decide whether to perform retry or redirect operation by judging the status code and exception type of the response.
3. Bridge Interceptor
- Location: After retrying and redirecting the interceptor.
-
effect: It is mainly responsible for converting user's requests into requests that comply with network transmission specifications. It will add some necessary request headers, such as
Content-Type
、Content-Length
、User-Agent
etc., and simultaneously handle the encoding and compression of the request body. In addition, it will also process the response, such as putting theContent-Encoding
The information is parsed and the response body is decoded accordingly. -
Source code analysis:exist
intercept
In the method, the corresponding request header will be added according to the situation of the request body, and then theThe method passes the processed request to the next interceptor, and finally processes the response and returns.
4. Cache Interceptor
- Location: After the bridge interceptor.
-
effect: Cache logic responsible for handling requests. It will depend on the requested cache policy (e.g.
Cache-Control
Header information) Check whether there are responses that meet the criteria in the local cache. If there is and the cache is valid, the cached response will be directly returned to avoid network requests; if the cache is invalid or does not exist, a network request will be initiated and the response will be stored in the cache. -
Source code analysis:exist
intercept
In the method, the matching response will be first looked up from the cache, and then the cache will be judged based on the request and cache situation. If cache is available, the cache response will be returned directly; otherwise, the callMethod initiates a network request and saves the response to cache.
5. Connect Interceptor
- Location: After the cache interceptor.
- effect: Responsible for establishing a connection to the server. It selects the appropriate connection (such as HTTP/1.1 or HTTP/2 connection) based on the requested URL and configuration, and performs TCP handshake and TLS negotiation (if it is an HTTPS request). At the same time, it manages the connection pool, reuses established connections, and reduces the overhead of connection establishment.
-
Source code analysis:exist
intercept
In the method, the available connections will be obtained from the connection pool. If there is no available connection, a new connection will be created, and then the connection will be established and handshake will be performed, and the connection will be passed to the next interceptor.
6. User-defined network interceptor (())
- Location: After connecting to the interceptor, it will only be executed when a network request is made.
- effect: Similar to user-defined interceptors, but it focuses more on handling network requests and responses. Since it is executed after the connection is established, the actual network connection information can be obtained, and the network requests and responses can be modified at a lower level, such as modifying the requested byte stream, monitoring network traffic, etc.
- Sample code:
import ; import ; import ; import ; public class NetworkLoggingInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = (); long t1 = (); (("Sending request %s on %s%n%s", (), (), ())); Response response = (request); long t2 = (); (("Received response for %s in %.1fms%n%s", ().url(), (t2 - t1) / 1e6d, ())); return response; } }
7. Server call interceptor (CallServerInterceptor)
- Location: The last interceptor of the interceptor chain.
- effect: Responsible for sending requests to the server and receiving the server's response. It writes the requested data to the network connection and then reads the response data returned by the server, including the response header and the response body.
-
Source code analysis:exist
intercept
In the method, the request body will be written to the connected output stream, the request header will be sent, and then the response header and response body will be read from the connected input stream, and finally the response object will be returned.
3. The difference between application interceptor and network interceptor
Apply interceptors
-
Add method:pass
().addInterceptor(Interceptor interceptor)
Method added. - Execution timing: Perform before all network-related operations, only the original request initiated by the application layer is processed.
- Features: It will not be affected by network operations such as redirection and retry, and each request will only pass through the application interceptor once. It can obtain the most original request and final response, which is suitable for logging, request header addition and other operations.
import ; import ; import ; import ; public class ApplicationInterceptorExample { public static void main(String[] args) throws IOException { CustomInterceptor customInterceptor = new CustomInterceptor(); OkHttpClient client = new () .addInterceptor(customInterceptor) .build(); Request request = new () .url("") .build(); Response response = (request).execute(); (().string()); } }
Network Interceptor
-
Add method:pass
().addNetworkInterceptor(Interceptor interceptor)
Method added. - Execution timing: After establishing a network connection and before sending a request to the server, all network requests will be processed, including redirection and retry requests.
-
Features:
- Details of the network layer can be handled, such as requested retry, redirection, etc.
- It may be performed multiple times, as redirection and retry can cause requests to pass through the network interceptor multiple times.
import ; import ; import ; import ; public class NetworkInterceptorExample { public static void main(String[] args) throws IOException { CustomInterceptor customInterceptor = new CustomInterceptor(); OkHttpClient client = new () .addNetworkInterceptor(customInterceptor) .build(); Request request = new () .url("") .build(); Response response = (request).execute(); (().string()); } }
4. Advanced application scenarios of interceptors
Cache Control Interceptor
An interceptor can be created to dynamically control cache policies, such as deciding whether to use cache based on network status or user settings.
import okhttp3.*; import ; public class CacheControlInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = (); if (isNetworkAvailable()) { // When the network is available, set the cache policy to cache for up to 60 seconds request = () .header("Cache-Control", "max-age=60") .build(); } else { // Force cache use when the network is unavailable request = () .header("Cache-Control", "only-if-cached") .build(); } return (request); } private boolean isNetworkAvailable() { // Implement network status check logic return true; } }
Timeout retry interceptor
An interceptor can be created to handle the request timeout, and when the request timeout, it will automatically retry a certain number of times.
import okhttp3.*; import ; public class RetryInterceptor implements Interceptor { private static final int MAX_RETRIES = 3; @Override public Response intercept(Chain chain) throws IOException { Request request = (); Response response = null; IOException exception = null; for (int i = 0; i < MAX_RETRIES; i++) { try { response = (request); if (()) { break; } } catch (IOException e) { exception = e; } } if (response == null) { throw exception; } return response; } }
Extended question:
How to ensure that each interceptor in the OKHttp interceptor chain can be executed in a predetermined order
Answer: The order of the interceptors of OKHttp is like a "relay race":
- The frame specifies a fixed runway with built-in interceptors(Retry → Bridge → Cache → Connect → Network Request);
- User interceptors are inserted into specific locations by type(Apply the interceptor at the starting point, and the network interceptor after the connection);
-
()
It is the baton to ensure that each interceptor handles the requests in sequence, and the responses are reflowed in reverse order, interlocking and without confusion.
principle:
Interceptorintercept
Method call
Each interceptor is implementedInterceptor
Interface, this interface has aintercept
method. existintercept
In the method, the passed in need is calledChain
The object'sproceed
Method, pass the request to the next interceptor. For exampleBridgeInterceptor
ofintercept
method:
@Override public Response intercept(Chain chain) throws IOException { Request userRequest = (); requestBuilder = (); // Process the request header RequestBody body = (); if (body != null) { MediaType contentType = (); if (contentType != null) { ("Content-Type", ()); } long contentLength = (); if (contentLength != -1) { ("Content-Length", (contentLength)); ("Transfer-Encoding"); } else { ("Transfer-Encoding", "chunked"); ("Content-Length"); } } Request networkRequest = (); // Call the method to pass the request to the next interceptor Response networkResponse = (networkRequest); // Process the response responseBuilder = () .request(userRequest); return (); }
existintercept
Called in the methodMethod will trigger the execution of the next interceptor, thereby ensuring that the interceptor chain is executed in sequence.
———————————————————————————————————————————
Detailed explanation of OkHttp cache mechanism (combined with high-frequency test points for Android interviews)
1. Cache core components and configurations
Cache
kind
effect: OkHttp's cache passesCache
Class implementation, based on disk storage (default memory-free cache, needs to be implemented manually).
initialization:
File cacheDir = new File((), "okhttp_cache"); OkHttpClient client = new () .cache(new Cache(cacheDir, 10 * 1024 * 1024)) // 10MB cache size .build();
Interview: The cache directory is usually placed in the application private directory (such asgetCacheDir()
) to avoid permission problems; the cache size needs to be set reasonably according to the business scenario, too large and waste storage, too small, resulting in low cache hit rate.
CacheInterceptor
Interceptor
-
Location: The third interceptor in the interceptor chain (located
RetryAndFollowUpInterceptor
andConnectInterceptor
between). - Core functions: Handling cache reading, writing and updating, is the core logical carrier of the cache mechanism.
2. Caching strategy (high-frequency test points for interviews)
OkHttp SupportHTTP standard caching policy(based onCache-Control
header) andCustomize the policy,passRequest
ofCacheControl
Object configuration, common strategies:
Forced cache (not interacting with the server)
-
CacheControl.FORCE_CACHE
: Priority is given to cache, exceptions are thrown when there is no cache (need to cooperatemax-stale
etc. parameters). - Scene: Completely offline scenarios, such as the bottom-up page.
Cache priority (request for network if there is no valid cache)
(() .maxStale(7, ) // Allow cache expires for 7 days.build())
-
process: Check the cache first, if the cache has not expired or is allowed
max-stale
, return directly; otherwise, request the network and respond to write to the cache.
Network priority (ignoring cache, only storing responses)
-
CacheControl.FORCE_NETWORK
: Directly request the network, and write the response result to the cache (applicable to real-time data).
Negotiate cache (verify cache validity with the server)
- Utilize
ETag
/If-None-Match
orLast-Modified
/If-Modified-Since
Header, server returns304 Not Modified
Time reuse cache. - Interview: Distinguish between forced cache (200 status code, directly read cache) and negotiated cache (304 status code, server verification required).
3. Cache storage structure and HTTP header analysis
Cache storage format
OkHttp will respond withBinary filesStored on disk, the file name is generated by the hash value of the URL, and contains two parts:
-
Response header file(
.headers
): StorageCache-Control
、ETag
Environmental information. - Response body file(No extension): Stores actual data.
Key HTTP header fields
Cache-Control
:
-
max-age
: - The cache validity period (seconds), the priority is higher than
Expires
。 -
no-cache
: Negotiation cache (verification of validity) is required.no-store
: Cache is prohibited. -
ETag
/Last-Modified
: Negotiate the core fields of cache, automatically processed by OkHttpIf-None-Match
andIf-Modified-Since
head.
4. Cache process and interceptor logic
- Cache read(
CacheInterceptor
First half) - Find responses matching the request from the cache (based on URL, method, header information).
- If there is a cache, according to
Cache-Control
Determine whether it is valid: - Valid: Return to cache directly (skip network requests).
- Expired but allowed
max-stale
: Return to cache and update network data asynchronously.
Network requests and cache writes (CacheInterceptor
Second half)
- After the network response is returned, according to
Cache-Control
Decide whether to write to the cache (such asmax-age > 0
)。 - Check the response status code before writing (only 200 OK and 304 will be cached) and extract the necessary header information for subsequent verification.
5. Memory cache and disk cache (interview is easy to get confused)
-
Disk Cache:OkHttp is built-in, through
Cache
Class configuration, persistent storage, suitable for large files or scenarios that require offline access. -
Memory cache: Need to be implemented manually (if used
LruCache
), OkHttp is not supported by default, and is used to accelerate hot data access and reduce disk IO. -
Interview question: "Is there any memory cache in OkHttp? How to implement it?" Answer: By default, only disk cache is available, and memory cache needs to be combined.
Interceptor
Manually implement, store processedResponse
Object.
6. Cache invalidation and update
Manually clear cache
().delete(); // Clear all caches().evictAll(); // Same as above(API difference)
Forced policy update
Add when initiating a request()
, force ignore cache and go to network requests.
7. Summary of high-frequency interview questions
"What are the OkHttp caching policies? How to achieve cache priority?"
Answer: SupportFORCE_CACHE
(Forced read cache),FORCE_NETWORK
(Forced network), negotiated cache (304), etc.; cache can be passed firstmaxStale
Allow expired caches to cooperate with network requests for updates.
“How to handle the 304 status code in the OkHttp cache?”
Answer: OkHttp automatic carryETag
GenerateIf-None-Match
Header. When the server returns 304, the local cache response body is reused and only the header information is updated (reduced traffic).
“The difference between OkHttp cache and browser cache?”
Answer: The core logic is consistent (based on HTTP headers), but OkHttp needs to be configured manually.Cache
Instance, and there is no memory cache by default; browser cache is automatically managed by the browser.
"What does the cache interceptor function? Where is it in the interceptor chain?"
Answer: Responsible for the read and write of the cache, located in the middle of the interceptor chain (retry, bridging, connection and network requests are not processed).Summarize
The OkHttp cache mechanism passesInterceptor chainandHTTP standard headerThe core of achieving efficient network request optimization lies in reasonable configurationCacheControl
Strategy, use negotiation cache to reduce server pressure, and combine disk/memory cache to improve performance. --
_____________________________________________________________________________
OkHttp's connection pool multiplexing is an important means to optimize network request performance, and its core is toConnectionPool
Manage underlying TCP connections to avoid the overhead of repeated connection establishments.
1. The core principle of OkHttp connection pool multiplexing
Target
Reuse connections with the same URL and the same protocol (HTTP/HTTPS), reduce the time-consuming and TCP three-way handshake and TLS handshake, and improve the request speed.
Core class: ConnectionPool
- effect: Maintain a connection queue, cache unclosed idle connections for reuse of subsequent requests.
-
Default configuration(
OkHttpClient
Created by default):
// Default connection pool in OkHttpClient source codeprivate static final ConnectionPool DEFAULT_CONNECTION_POOL = new ConnectionPool( 5, // Maximum number of idle connections (default 5) 5, // Idle connection survival time (default 5 minutes));
Key parameters:
-
maxIdleConnections
: Maximum number of idle connections, if the number exceeds the oldest connection is cleaned. -
keepAliveDuration
: The maximum survival time of an idle connection in the pool, and the timeout is closed.
Connection multiplexing conditions
- The requested URL
host
andport
Same, and the protocol (HTTP/HTTPS) is consistent. - The connection is in "idle" (i.e. no request is currently in use but has not timed out).
2. How to use connection pool multiplexing?
1. Default use (no additional configuration required)
OkHttpClient enables connection pooling by default, no manual settings are required, the sameOkHttpClient
All requests for the instance share the same connection pool:
OkHttpClient client = new () .connectTimeout(10, ) .build(); // Use the default internallyConnectionPool
2. Custom connection pool configuration (optional)
If you need to adjust the default parameters (such as increasing the number of idle connections or survival time), you can use itconnectionPool()
Method settings:
OkHttpClient client = new () .connectionPool(new ConnectionPool( 10, // Maximum number of idle connections is set to 10 10, // Set the idle connection survival time to 10 minutes )) .build();
3. Connection pool life cycle
-
Automatic cleaning:OkHttp through background thread (
CleanupRunnable
) Check regularly (every 5 seconds), clearing out idle connections that are timed out. - Manual cleaning(Rare scenario): If you need to release resources immediately (such as when the application exits), you can call:
().evictAll(); // Clear all connections
3. Source code-level implementation details (FAQs in interviews)
Connection acquisition process
When a request is initiated, OkHttp will firstConnectionPool
Find available free connections in:
// Find the core logic of the connectionRealConnection get(Address address, StreamAllocation streamAllocation) { // traverse the connections in the connection pool to find connections that match the address and are idle for (RealConnection connection : connections) { if ((address, streamAllocation)) { (connection); return connection; } } return null; // No connection is available, create a new connection}
isEligible
The method determines whether the connection meets the multiplexing conditions (host, port, and protocol are consistent, and the maximum number of requests is not reached).
Connection release with idle mark
Once the request is complete, the connection is not closed immediately, but is marked "idle" and put back into the connection pool:
// Release the logic of the connectionvoid release(StreamAllocation streamAllocation) { if (streamAllocation == null) return; (); if (allocationCount > 0 || noNewStreams) { return; // The connection is still in use } // The connection becomes idle and joins the idle queue of the connection pool (this); }
Cleanup mechanism
ConnectionPool
passCleanupRunnable
Thread timed executioncleanup()
Method, remove connections that timed out or exceed the maximum idle number:
// Clean up logicprivate final Runnable cleanupRunnable = () -> { while (true) { long waitNanos = cleanup(()); // Perform cleanup and return to the next waiting time if (waitNanos == -1) return; // No connections that need to be cleaned, exit if (waitNanos > 0) { synchronized (this) { try { wait(waitNanos / 1000000, (int) (waitNanos % 1000000)); } catch (InterruptedException e) { return; } } } } };
4. High-frequency interview questions and answers
1. Why do you need connection pool reuse? What are the advantages over HTTPURLConnection?
reason: Avoid repeated establishment of TCP connections (three-way handshake) and TLS handshake (HTTPS scenarios), reducing latency and resource consumption.
Advantages:
- HTTPURLConnection does not support connection reuse by default (manual configuration is required
(true)
, and complex management); - OkHttp's
ConnectionPool
Automatically manage connection lifecycle, thread-safe, out of the box.
2. How to determine whether two requests can reuse the same connection?
Must meet:
- URL's
host
andport
same; - The protocol is the same (both HTTP or both HTTPS);
- The connection is idle (not occupied and timed out).
3. Will the connection in the connection pool always exist? How to avoid memory leaks?
Won't:
- Exceed
maxIdleConnections
idle connections will be cleaned; - Exceed
keepAliveDuration
idle connections will be closed; - When the application exits, it is recommended to call it
()
Release all connections.
Best Practices: Use single caseOkHttpClient
(Avoid creating multiple instances resulting in multiple connection pools) and set them up reasonablymaxIdleConnections
(Usually the default value is enough).
4. What is the relationship between the connection pool and the cache mechanism (CacheInterceptor)?
- Connection poolOptimized is the performance of the "network connection layer" (reducing connection establishment overhead);
- Cache mechanismWhat is optimized is the performance of the "application layer" (directly returning to local cache to avoid network requests);
- Both can be used at the same time to improve performance together.
V. Best Practices
Singleton mode: Share one globallyOkHttpClient
Instance, avoid repeated creation of connection pools:
public class OkHttpSingleton { private static OkHttpClient client; public static OkHttpClient getInstance() { if (client == null) { synchronized () { if (client == null) { client = new () .connectionPool(new ConnectionPool(5, 5, )) .build(); } } } return client; } }
- Combined with HTTPS optimization: When multiplexing the connection, the TLS handshake is only performed when the connection is established for the first time, and subsequent requests directly multiplex the established encrypted channel.
-
Monitoring and debugging:pass
EventListener
Listen to connection pool events (such as connection creation, reuse, and release) and troubleshoot performance issues.
Summarize
OkHttp's connection pool multiplexing is passedConnectionPool
Automatically manage idle connections to significantly improve network request efficiency. No manual intervention is required when using, just configure the parameters reasonably (or use the default values) and follow the singleton mode sharingOkHttpClient
Just an example.
Extended question:
1. How to implement connection pool multiplexing in OkHttp? (High-frequency questions)
Core answer points:
-
ConnectionPool Components:OkHttp by
ConnectionPool
Manage connections, maintain 5 idle connections by default (maxIdleConnections
), survival time 5 minutes (keepAliveDuration
)。 - Multiplexing logic: New requests preferentially find matching idle connections (same host, port, protocol) from the connection pool, avoid repeated creation of TCP connections and TLS handshakes, and reduce latency.
-
Connection Recycling: After the request is completed, the connection will not be closed immediately, but will be placed in the pool for reuse; if the idle time exceeds the threshold or the number of connections exceeds the upper limit, it will pass through the background thread (
cleanupRunnable
) Clean out expired connections regularly. -
Interview bonus points: Comparing HTTP/1.1's
Connection: Keep-Alive
, OkHttp is more efficient, supports automatic management of connection life cycle and reduces resource consumption.
2. What is the core strategy of the OkHttp caching mechanism? How to configure it? (Required question)
Core answer points:
Two-tier cache:
-
Memory cache(
CacheInterceptor
Management): Store response data, quickly respond to repeated requests, and reduce CPU and memory overhead. -
Disk Cache(
Cache
Class, needs to be created manually): Persistent storage to deal with APP restart or long-term unrequested scenarios. -
Cache Policy:pass
CacheControl
Header configuration, such asFORCE_CACHE
(Preferential reading cache),FORCE_NETWORK
(Forced Internet access),CACHE_ELSE_NETWORK
(On the network after the cache expires). -
Interview Trap: Need to be distinguishedStrong cache(
304 Not Modified
)andNegotiate cache(Server verification of cache validity), OkHttp built-in interceptor automatically handles cached response codes. -
Configuration example: Create
Cache
Object and set the size (such asnew Cache(cacheDir, 10 * 1024 * 1024)
),pass().cache(cache)
Bind.
3. What is the function of Interceptor Chain? How to implement a custom interceptor? (Principle question)
Core answer points:
- Responsibility chain model:OkHttp handles requests and responses through interceptor chains, includingRetry and redirect、Bridging (add request header/process response body)、cache、Connection establishment、Network requestBuilt-in interceptors.
- Execution order: User-defined interceptor → Built-in retry interceptor → Bridge interceptor → Cache interceptor → Connection interceptor → Network interceptor → Call server interceptor.
-
Custom scene: Used to add public request headers (such as tokens), log printing, response data analysis/modification, and implement
Interceptor
Interfaceintercept
Method, call(request)
Pass the request. - Interview key: Emphasizes the "middleware" characteristics of the interceptor, which can extend functions without modifying the core code, and complies with the principle of opening and closing.
4. What is the difference between synchronous requests and asynchronous requests? How to implement thread switching? (Thread question)
Core answer points:
-
How to execute: synchronous: Blocking the current thread, calling it in the main thread will cause ANR, and it needs to be executed in the child thread, and it will be returned directly
Response
。 -
asynchronous:pass
Dispatcher
Scheduled to thread pool (defaultExecutorService
), callbackCallback
In the child thread, it needs to be manually passedHandler
Switch back to the main thread. -
Thread management:
Dispatcher
Control the maximum number of concurrent requests (default 64, 5 on the same host), asynchronous requests passAsyncCall
Encapsulate, put it into a queue or execute it directly. -
Interview Trap: Avoid confusion "Whether the asynchronous callback is in the main thread", OkHttp is not responsible for thread switching, and needs to be handled by the developer (such as
runOnUiThread
)。
5. What are the advantages of OkHttp over Volley or HttpURLConnection? (Comparison question)
Core answer points:
- Performance optimization: Connection pool multiplexing, cache policy, SPDY/HTTP/2 support (reduces the number of TCP connections), making network requests more efficient.
- Extensibility: The interceptor mechanism is flexible, which is convenient for adding logs, retry, encryption and other functions, while Volley is more suitable for small short connection requests.
- stability: Built-in retry mechanism (automatically handle connection timeout and redirection), supports streaming response processing (large file download), suitable for complex network scenarios.
- Extra points for interview: Based on actual projects, explain the advantages of OkHttp in handling high concurrency, large files, and complex network environments.
6. How to optimize the network request performance of OkHttp? (Practical question)
Core answer points:
-
Connection pool tuning: Adjust according to business scenarios
maxIdleConnections
andkeepAliveDuration
(For example, the number of connections of high-frequency interfaces is increased). -
Cache Policy: Set the cache validity period reasonably (
), reduce invalid network requests.
-
HTTPS Optimization:use
CertificatePinner
Fixed certificates to avoid time-consuming SSL handshakes; enable HTTP/2 (requires server support). -
Concurrent control:pass
and
setMaxRequestsPerHost
Limit concurrency and avoid resource exhaustion.
This is the article about the OKHttp interceptor and cache of Android learning summary. For more related contents of Android OKHttp interceptor, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!