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

来源:互联网 发布:北汽黄骅分公司 知乎 编辑:程序博客网 时间:2024/05/16 08:51

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

标签: retrofit日志okhttpLoggingIntercepto
4025人阅读 评论(4)收藏举报
分类:
作者同类文章X

    目录(?)[+]

    1. 步骤
    2. 日志级别

    用过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'
    • 1
    • 2
    • 3

    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);
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3、配置okhttp

    client = new OkHttpClient.Builder()                    .cache(cache)                    .addInterceptor(loggingInterceptor)                    .connectTimeout(mTimeOut, TimeUnit.SECONDS)                    .readTimeout(mTimeOut, TimeUnit.SECONDS)                    .writeTimeout(mTimeOut, TimeUnit.SECONDS)                    .build();
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    4、配置retrofit

    Retrofit retrofit = new Retrofit.Builder()                    .baseUrl(userCenter)                    .client(client)                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())                    .addConverterFactory(GsonConverterFactory.create())                    .build();
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    日志级别

    大家看到配置loggingInterceptor的时候

    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    • 1

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

    1、NONE

    没有任何log
    • 1

    2、BASIC
    请求/响应行

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

    这里写图片描述

    3、HEADERS
    请求/响应行 + 头

    这里写图片描述

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

    2
    0
     
     

      相关文章推荐
    • 更新到Retrofit2的一些技巧
    • Hadoop生态系统零基础入门
    • <Retrofit2> 打印网络请求日志
    • 系统集成工程师必过冲刺!
    • Retrofit2打印 网络请求日志
    • 征服React Native我有妙招
    • Retrofit使用Log拦截器在控制台输出Log
    • FFmpeg音视频高级开发实战
    • Android retrofit 日志拦截器
    • 5天搞定深度学习框架-Caffe
    • 按钮OnClick实现的三种方法
    • Python数据分析经典案例解析
    • 树形结构的数据库
    • 得到进程ID号
    • 使用convertView优化ListView
    • Retrofit打印请求地址和返回内容
    原创粉丝点击