背景
在使用Android retrofit+rxjava时,想获知网络请求的一些参数,方便调试,比如:请求地址、请求响应时间、请求响应消息体等内容,虽然部分可以通过每个接口进行获知,但是这样极其不方便,那么有没有可以统一设置的方法呢?请接下去看。
日志拦截器
retrofit是使用okhttp3,做为网络请求,okhttp3有个Interceptor接口,可以对请求和响应进行拦截。通过这个机制,我们可以设计自己的一套日志拦截器,打印一些必要的信息。
自定义拦截器
首先要自己定义一个拦截器类,并实现Interceptor接口,在里面打印一些信息,如下LogInterceptor.java类。
public class LogInterceptor implements Interceptor{
public static final String TAG = "LogInterceptor.java";
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
//the request url
String url = request.url().toString();
//the request method
String method = request.method();
long t1 = System.nanoTime();
HLog.d(TAG,String.format(Locale.getDefault(),"Sending %s request [url = %s]",method,url));
//the request body
RequestBody requestBody = request.body();
if(requestBody!= null) {
StringBuilder sb = new StringBuilder("Request Body [");
okio.Buffer buffer = new okio.Buffer();
reques