前言
我们应用中经常出现请求其他三方接口,这也是经常会出错,找当时请求参数,返回结果比对的情况。如果自己加打印,很多时候会忘记。这里通过对Okhttp工具添加拦截器方式,将需要入参出参进行打印。
实践
一、引入maven 依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
</dependency>
二、创建日志拦截器
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import okhttp3.*;
import okio.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* @author Administrator
*/
public class LoggingInterceptor implements Interceptor {
private Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
logForRequest(request);
TimeInterval timer = DateUtil.timer();
Response response = chain.proceed(request);
return logForResponse(response, timer);
}
private Response logForResponse(Response response, TimeInterval timer) {
try {
Response.Builder builder = response.newBuilder();
Response clone = builder.build();
logger.info("=========repose==log==start======");
logger.info(String.format("repose url:%s,code:%s,time is:%s,headers:%s", clone.request().url(), clone.code(), timer.intervalMs() + "ms", clone.protocol()));
ResponseBody body = clone.body();
if (body != null) {
MediaType mediaType = body.contentType();
if (mediaType != null && isText(mediaType)) {
String content = body.string();
logger.info(String.format("message:%s,contentType:%s,content is:%s,", clone.message(), mediaType.toString(),content ));
body = ResponseBody.create(mediaType, content);
return response.newBuilder().body(body).build();
}
}
} catch (Exception e) {
logger.warn("print reponse error", e);
}finally {
logger.info("=========repose==log==end======");
}
return response;
}
private void logForRequest(Request request) {
String url = request.url().toString();
String method = request.method();
Headers headers = request.headers();
String headerStr = headers != null && headers.size() > 0 ? headers.toString() : "";
logger.info("=========request==log==start======");
logger.info(String.format("request url:%s,method:%s,headers:%s", url, method, headerStr));
RequestBody requestBody = request.body();
if (requestBody != null) {
MediaType mediaType = requestBody.contentType(