1. 程式人生 > >Retrofit2.0新增日誌攔截器列印URL一級返回資料

Retrofit2.0新增日誌攔截器列印URL一級返回資料


 
  
  

  
//定製OkHttp
OkHttpClient.Builder httpClientBuilder = new OkHttpClient
        .Builder();
if (BuildConfig.DEBUG) {//釋出版本不再列印 
    // 日誌顯示級別 
    HttpLoggingInterceptor.Level level= HttpLoggingInterceptor.Level.BASIC; 
    //新建log攔截器 
    HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor(new 
HttpLoggingInterceptor.Logger() { @Override public void log(String message) { LogUtil.e("test","OkHttp====Message:"+message); } }); loggingInterceptor.setLevel(level); //OkHttp進行新增攔截器loggingInterceptor httpClientBuilder.addInterceptor(loggingInterceptor);
} Retrofit retrofit = new Retrofit.Builder() .baseUrl(HttpHelper.HOST.toString()) .client(httpClientBuilder.build()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build();

HttpLoggingInterceptor.Level共包含四個級別:NONE、BASIC、HEADER、BODY

NONE 不記錄

BASIC 請求/響應行--> POST /greeting HTTP/1.1 (3-byte body)<-- HTTP/1.1 200 OK (22ms, 6-byte body)

HEADER 請求/響應行 + 頭--> Host: example.comContent-Type: plain/textContent-Length: 3<-- HTTP/1.1 200 OK (22ms)Content-Type: plain/textContent-Length: 6

BODY 請求/響應行 + 頭 + 體

可以通過 setLevel 改變日誌級別