retrofit 实现打印请求 log 日志

本贴最后更新于 2683 天前,其中的信息可能已经时过境迁

使用retrofit 打印出网络请求日志,包括请求urll、返回内容等。要实现打印日志,就要用到HttpLoggingInterceptor这个类。 

build.gradle 导入

compile 'com.squareup.okhttp3:okhttp:3.+'
compile 'com.squareup.okio:okio:1.+'
compile 'com.squareup.okhttp3:logging-interceptor:3.+'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

主要导入的是compile 'com.squareup.okhttp3:logging-interceptor:3.+' 

初始化okhttp

private static void initOkHttp() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    if (BuildConfig.DEBUG) {
        // https://drakeet.me/retrofit-2-0-okhttp-3-0-config
        HttpLoggingInterceptor loggingInterceptor =new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
        builder.addInterceptor(loggingInterceptor);
    }
    // http://www.jianshu.com/p/93153b34310e
    File cacheFile = new File(Constants.PATH_CACHE);
    Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
    Interceptor cacheInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException{
            Request request = chain.request();
            if (!NETworkUtils.isConnected(MyApp.getInstance().getApplicationContext())){
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }
            Response response = chain.proceed(request);
            if (NETworkUtils.isFastMobileNetwork(MyApp.getInstance().getApplicationContext())){
                int maxAge = 0;
                // 有网络时,不缓存,最大保存时长为0
                response.newBuilder()
                   .header("Cache-Control","public,max-age="+maxAge)
                   .removeHeader("Pragma")
                   .build();
            } else {
                // 无网络时,设置超时为4周
                int maxStale = 60 * 60 * 24 * 28;
                response.newBuilder()
                   .header("Cache-Control", "public,only-if-cached, max-stale="+maxStale)
                   .removeHeader("Pragma")
                   .build();
            }

            return response;
        }
    };
    //设置缓存
    builder.addNetworkInterceptor(cacheInterceptor);
    builder.addInterceptor(cacheInterceptor);
    builder.cache(cache);
    //设置超时
    builder.connectTimeout(10, TimeUnit.SECONDS);
    builder.readTimeout(20, TimeUnit.SECONDS);
    builder.writeTimeout(20, TimeUnit.SECONDS);
    //错误重连
    builder.retryOnConnectionFailure(true);
    okHttpClient = builder.build();
}

配置 retrofit

Retrofit fpRetrofit = new Retrofit.Builder()
        .baseUrl(FPApis.HOST)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build();

日志级别

loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);

除了 BASIC 级别外,还有 NONE、HEADERS、BODY。

  • NONE 

    没有任何 log。

  • HEADERS

    请求/响应行 + 头

  • BODY

    请求/响应行 + 头 + 体

  • BASIC

    请求/响应行 

  • B3log

    B3log 是一个开源组织,名字来源于“Bulletin Board Blog”缩写,目标是将独立博客与论坛结合,形成一种新的网络社区体验,详细请看 B3log 构思。目前 B3log 已经开源了多款产品:SymSoloVditor思源笔记

    1090 引用 • 3467 回帖 • 297 关注
  • 源码阁
    10 引用 • 5 回帖
  • Android

    Android 是一种以 Linux 为基础的开放源码操作系统,主要使用于便携设备。2005 年由 Google 收购注资,并拉拢多家制造商组成开放手机联盟开发改良,逐渐扩展到到平板电脑及其他领域上。

    331 引用 • 315 回帖 • 83 关注
  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3165 引用 • 8206 回帖 • 1 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...