HttpLoggingInterceptor消息攔截器

為什么要用消息攔截器?
因?yàn)橛袝r(shí)候接口不同在排錯(cuò)的時(shí)候 需要先從接口的響應(yīng)中做分析。利用了消息攔截器可以清楚的看到接口返回的所有內(nèi)容。不需要重新使用fildder等抓包工具來做分析。

1.添加依賴

//okhttp的log信息
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

2.在合適的位置初始化(這里放在了構(gòu)造,因?yàn)槭菃卫?,響?yīng)的攔截器也只new一次)

    private HttpMethod() {
       HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                try {
                    String text = URLDecoder.decode(message, "utf-8");
                    Log.e("OKHttp-----", text);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    Log.e("OKHttp-----", message);
                }
            }
        });
        //這里可以builder(). 添加更多的內(nèi)容 具體看需求
        mClient = new OkHttpClient.Builder().addInterceptor(interceptor).build();
        //這行必須加 不然默認(rèn)不打印
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    }

3.在retrofit中設(shè)置httpclient

   Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        //添加HttpClient
                        .client(mClient)
                        .build();
                mApiService = retrofit.create(ApiService.class);

setlevel用來設(shè)置日志打印的級(jí)別,共包括了四個(gè)級(jí)別:NONE,BASIC,HEADER,BODY
BASEIC:請(qǐng)求/響應(yīng)行
HEADER:請(qǐng)求/響應(yīng)行 + 頭
BODY:請(qǐng)求/響應(yīng)航 + 頭 + 體

以下是BODY級(jí)別的 打印的日志如下


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容