目录
OkHttp 是一个强大的 HTTP 客户端,广泛用于 Android 开发中。拦截器(Interceptor)是 OkHttp 的一个核心功能,允许开发者在请求和响应的生命周期中插入自定义逻辑。拦截器可以用于多种场景,如日志记录、添加公共请求头、处理缓存、重试策略等。
OkHttp 提供了两种类型的拦截器:
- 应用拦截器(Application Interceptor)
- 网络拦截器(Network Interceptor):
应用拦截器(Application Interceptor)
作用
- 作用于应用层,通常用于添加公共请求头、日志记录等。
- 不会被重试机制影响。
使用
1. 添加公共请求头
应用拦截器可以用于为所有请求添加公共请求头:
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class HeaderInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request newRequest = originalRequest.newBuilder()
.header("Authorization", "Bearer your_token")
.header("Accept", "application/json")
.build();
return chain.proceed(newRequest);
}
}
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new HeaderInterceptor())
.build();
2. 日志记录
应用拦截器可以用于记录请求和响应的日志:
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
System.out.println(String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
System.out.println(String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
网络拦截器(Network Interceptor)
作用
- 作用于网络层,通常用于监控网络请求和响应、处理缓存等。
- 可以读取和修改网络请求和响应。
使用
1. 处理缓存
网络拦截器可以用于处理缓存策略:
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class CacheInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!isNetworkAvailable()) {
request = request.newBuilder()
.cacheControl(new CacheControl.Builder()
.onlyIfCached()
.maxStale(7, java.util.concurrent.TimeUnit.DAYS)
.build())
.build();
}
return chain.proceed(request);
}
private boolean isNetworkAvailable() {
// 检查网络连接状态
return true; // 替换为实际的网络状态检查逻辑
}
}
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(new CacheInterceptor())
.build();
2. 监控网络请求和响应
网络拦截器可以用于监控网络请求和响应的详细信息:
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class NetworkLoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
System.out.println("Network request: " + request.url());
Response response = chain.proceed(request);
System.out.println("Network response: " + response.code() + " " + response.message());
return response;
}
}
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(new NetworkLoggingInterceptor())
.build();