1. 程式人生 > >retrofit2.0使用攔截器Interceptor統一列印請求與響應的json

retrofit2.0使用攔截器Interceptor統一列印請求與響應的json

先新增依賴:
compile ‘com.squareup.retrofit2:retrofit:2.1.0’
compile ‘com.squareup.retrofit2:converter-gson:2.1.0’
compile ‘com.squareup.okhttp3:logging-interceptor:3.1.2’

二:okhttp已經為我們提供了一個Interceptor的實現類:HttpLoggingInterceptor。只要稍作設定就可以:

 HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger
() { @Override public void log(String message) { // Timber.tag("OkHttp").d(message); // Logger.e("okhttp",message); Log.e("okhttp",message); } }); logging.setLevel(HttpLoggingInterceptor.Level.BODY);//Level中還有其他等級 OkHttpClient client = new OkHttpClient.Builder
() .addInterceptor(logging) .build();

三:使用

 Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.douban.com/v2/")
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                .client(client)//新增上面設定好的OkHttpClient
                .build
();

下面是請求的程式碼:

 RetrofitService service = retrofit.create(RetrofitService.class);
        Call<Book> call =  service.getSearchBook("金瓶梅", null, 0, 1);

        call.enqueue(new Callback<Book>() {
            @Override
            public void onResponse(Call<Book> call, Response<Book> response) {
                button.setText(response.body()+"");
//                Log.e("Json",""+response.body().toString());
            }
            @Override
            public void onFailure(Call<Book> call, Throwable t) {
            }
        });

接下我們檢視日誌:
這裡寫圖片描述