Retrofit打印请求地址和返回内容

用过retrofit的同学,肯定会很爽,因为用起来实在是方便。但是我之前在使用retrofit的时候,发现没法打印出网络请求日志,包括请求urll、返回内容等。要实现打印日志,就要用到HttpLoggingInterceptor这个类。下面给大家讲一下如何打印出这些内容。

步骤

1、导入库

    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

2、初始化HttpLoggingInterceptor

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
                Log.i("RetrofitLog","retrofitBack = "+message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

3、配置okhttp

client = new OkHttpClient.Builder()
                    .cache(cache)
                    .addInterceptor(loggingInterceptor)
                    .connectTimeout(mTimeOut, TimeUnit.SECONDS)
                    .readTimeout(mTimeOut, TimeUnit.SECONDS)
                    .writeTimeout(mTimeOut, TimeUnit.SECONDS)
                    .build();

4、配置retrofit

Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(userCenter)
                    .client(client)
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

日志级别

大家看到配置loggingInterceptor的时候

loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

类型为BASIC,其实日志级别分为4类:NONE、BASIC、HEADERS、BODY。
大家看下我打印出来的日志,就知道这4类的区别了。

1、NONE

没有任何log

2、BASIC
请求/响应行

basic的格式:
--> POST 地址 http/1.1 (0-byte body)
<-- 200 OK 地址 (154ms, unknown-length body)

这里写图片描述

3、HEADERS
请求/响应行 + 头

这里写图片描述

4、BODY
请求/响应行 + 头 + 体
这里写图片描述

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值