使用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
请求/响应行
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于