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