okhttp3日志拦截器,打印请求信息

okhttp3日志拦截器,打印请求信息

导入包

		<dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>logging-interceptor</artifactId>
            <version>3.5.0</version>
        </dependency>

新建日志类

public class HttpLogger implements HttpLoggingInterceptor.Logger {
    @Override
    public void log(String s) {
        System.out.println(s);
    }
}

初始化okHttpClient

@Configuration
public class OkHttpClientConfig {

   

    @Bean
    public OkHttpClient okHttpClient() {
        Interceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger()).setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient(
                new okhttp3.OkHttpClient.Builder()
                        .readTimeout(5, TimeUnit.SECONDS)
                        .connectTimeout(5, TimeUnit.SECONDS)
                        .writeTimeout(5, TimeUnit.SECONDS)
                        .connectionPool(new ConnectionPool())
                        .addInterceptor(new SignInterceptor())//业务拦截器
                        .addNetworkInterceptor(logInterceptor)//日志拦截器
                        .build()
        );
        return okHttpClient;
    }
}

效果

--> POST https://xxx http/1.1
Content-Length: 67
Accept: */*
token: xx
version: xxx
Host: xxx
Connection: xx
Accept-Encoding: gzip
User-Agent: okhttp/3.14.6

{
  "pageNum" : 1,
  "pageSize" : 10
}
--> END POST (67-byte body)
<-- 200 OK https://xxx (466ms)
Date: Tue, 18 May 2021 07:06:22 GMT
Content-Type: application/json;charset=UTF-8
Content-Length: 201
Connection: keep-alive

{"data":null,"code":"xxx","msg":"网络连接异常","errorMsg":"","traceId":"","requestId":"xx","rt":0,"success":false}
<-- END HTTP (201-byte body)
上一篇:某手 v8.x 签名计算方法(一) 先从抓包说起


下一篇:OKhttpClient 连接池优化