OkHttp 3 配置 日志拦截器

依赖 配置fastjson是需要格式化输出

implementation 'com.squareup.retrofit2:retrofit:2.11.0'
implementation 'com.alibaba.fastjson2:fastjson2:2.0.52'
implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.12'

声明拦截器

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import okhttp3.*;
import okio.Buffer;
import okio.BufferedSource;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class LogInterceptor implements Interceptor {
    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        // 拿到请求参数
        Request request = chain.request();
        // 拿到请求 body
        RequestBody body = request.body();
        String bodyString = "";
        String responseBodyString;
        //对请求进行加密
        if (body != null) {
            Buffer buffer = new Buffer();
            body.writeTo(buffer);
            //将body 转成字符串,然后进行加密
            bodyString = buffer.readString(StandardCharsets.UTF_8);
        }
        //对响应进行解密
        Response response = chain.proceed(request);
        {
            ResponseBody responseBody = response.body();
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.getBuffer();
            responseBodyString = buffer.clone().readString(StandardCharsets.UTF_8);
        }
        printLog(request, response, bodyString, responseBodyString);
        return response;
    }

    private void printLog(Request request, Response response, String reqBody, String respBody) {
        //判断是否是json格式
        if (!reqBody.startsWith("{")) {
            String log = String.format("""
                        请求成功:%s
                        RequestBody:%s
                        ResponseBody:%s
                        """,
                    request.url(),
                    reqBody,
                    respBody
            );
            System.out.println(log);
            return;
        }
        String log = String.format("""
                        请求成功:%s
                        RequestBody:%s
                        ResponseBody:%s
                        """,
                request.url(),
                JSON.toJSONString(JSON.parseObject(reqBody), JSONWriter.Feature.PrettyFormat),
                JSON.toJSONString(JSON.parseObject(respBody), JSONWriter.Feature.PrettyFormat)
        );
        System.out.println(log);
    }
}

使用,拦截器的添加时机要在第一位,不能比别的拦截器晚添加,否则会影响日志结果

OkHttpClient.Builder clientBuilder=  new OkHttpClient().newBuilder()
                //日志拦截器
                .addInterceptor(new LogInterceptor());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值