okhttp 拦截器用过那些? 什么情况下用的?如何使用?

目录

  • [OkHttp 提供了两种类型的拦截器:](#OkHttp 提供了两种类型的拦截器:)
    • [应用拦截器(Application Interceptor)](#应用拦截器(Application Interceptor))
      • 作用
      • 使用
        • [1. 添加公共请求头](#1. 添加公共请求头)
        • [2. 日志记录](#2. 日志记录)
    • [网络拦截器(Network Interceptor)](#网络拦截器(Network Interceptor))
      • 作用
      • 使用
        • [1. 处理缓存](#1. 处理缓存)
        • [2. 监控网络请求和响应](#2. 监控网络请求和响应)

OkHttp 是一个强大的 HTTP 客户端,广泛用于 Android 开发中。拦截器(Interceptor)是 OkHttp 的一个核心功能,允许开发者在请求和响应的生命周期中插入自定义逻辑。拦截器可以用于多种场景,如日志记录、添加公共请求头、处理缓存、重试策略等。

Okhttp之五种拦截器

OkHttp 提供了两种类型的拦截器:

  • 应用拦截器(Application Interceptor)
  • 网络拦截器(Network Interceptor):

应用拦截器(Application Interceptor)

作用

  • 作用于应用层,通常用于添加公共请求头、日志记录等。
  • 不会被重试机制影响。

使用

1. 添加公共请求头

应用拦截器可以用于为所有请求添加公共请求头:

java 复制代码
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. 日志记录

应用拦截器可以用于记录请求和响应的日志:

java 复制代码
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. 处理缓存

网络拦截器可以用于处理缓存策略:

java 复制代码
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. 监控网络请求和响应

网络拦截器可以用于监控网络请求和响应的详细信息:

java 复制代码
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();
相关推荐
.豆鲨包12 小时前
【Android】OkHttp的使用及封装
android·java·okhttp
华科易迅13 小时前
Vue通过Ajax获取后台路由信息
vue.js·ajax·okhttp
studyForMokey2 天前
【Android面试】OkHttp & Retrofit 专题
android·okhttp·面试
fLDiSQV1W3 天前
springMVC-HTTP消息转换器与文件上传、下载、异常处理
网络协议·http·okhttp
弹简特5 天前
【JavaEE24-后端部分】 从“手动锁门”到“保安统一站岗”:Spring Boot 拦截器轻松搞定登录校验
java·spring boot·拦截器
Ttang236 天前
Java爬虫:Jsoup+OkHttp实战指南
java·爬虫·okhttp
李庆政3706 天前
OkHttp的基本使用 实现GET/POST请求 authenticator自动认证 Cookie管理 请求头设置
java·网络协议·http·okhttp·ssl
无名-CODING7 天前
Java 爬虫进阶:动态网页、多线程与 WebMagic 框架实战
java·爬虫·okhttp
小李云雾8 天前
零基础-从ESS6基础到前后端联通实战
前端·python·okhttp·中间件·eclipse·html·fastapi
亿牛云爬虫专家8 天前
爬虫踩坑实录:OkHttp 接入爬虫代理报 Too many tunnel connections attempted 深度解析
爬虫·okhttp·https·爬虫代理·connect·隧道代理·ip 切换