依赖 配置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());