其他分享
首页 > 其他分享> > okhttp3日志拦截器,打印请求信息

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)

标签:拦截器,okhttp3,OkHttpClient,new,日志,okHttpClient,public
来源: https://blog.csdn.net/qq_41250357/article/details/116990359