在網(wǎng)絡(luò)請求的時候我們一般會打印日志掂僵,包含請求地址、請求參數(shù)顷歌、返回結(jié)果锰蓬、請求耗時等。
在之前的操作中眯漩,可能會芹扭,在Request執(zhí)行的時候打印一下,Response返回結(jié)果的時候打印一下坤塞。那么這樣在如果同時多個請求的情況下就會產(chǎn)生混亂冯勉,日志里會出現(xiàn)并列多個請求,并列多個結(jié)果摹芙。那么使用Okhttp的過濾器便能解決這一問題
代碼如下:
public class LogInterceptor implements Interceptor {
public static String TAG = "LogInterceptor";
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long startTime = System.currentTimeMillis();
okhttp3.Response response = chain.proceed(chain.request());
long endTime = System.currentTimeMillis();
long duration=endTime-startTime;
okhttp3.MediaType mediaType = response.body().contentType();
String content = response.body().string();
Log.d(TAG,"\n");
Log.d(TAG,"----------Start----------------");
Log.d(TAG, "| "+request.toString());
String method=request.method();
if("POST".equals(method)){
StringBuilder sb = new StringBuilder();
if (request.body() instanceof FormBody) {
FormBody body = (FormBody) request.body();
for (int i = 0; i < body.size(); i++) {
sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
}
sb.delete(sb.length() - 1, sb.length());
Log.d(TAG, "| RequestParams:{"+sb.toString()+"}");
}
}
Log.d(TAG, "| Response:" + content);
Log.d(TAG,"----------End:"+duration+"毫秒----------");
return response.newBuilder()
.body(okhttp3.ResponseBody.create(mediaType, content))
.build();
}
}
Get和Post是兩種常見的請求方式灼狰,網(wǎng)上很多文章只是說明了打印請求地址,在Get請求時候這個參數(shù)會拼接在請求地址后面浮禾,而Post請求的參數(shù)是在請求體里面的交胚,因此必需要先獲取到請求體然后遍歷份汗,拿到請求參數(shù)。因此上面代碼中的這部分是為了打印Post請求參數(shù)而來蝴簇。
String method=request.method();
if("POST".equals(method)){
StringBuilder sb = new StringBuilder();
if (request.body() instanceof FormBody) {
FormBody body = (FormBody) request.body();
for (int i = 0; i < body.size(); i++) {
sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
}
sb.delete(sb.length() - 1, sb.length());
Log.d(TAG, "| RequestParams:{"+sb.toString()+"}");
}
}
具體過濾器使用方式很簡單在實例化httpClient的時候addInterceptor即可:
OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(new LogInterceptor())
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.retryOnConnectionFailure(false)
.build();
據(jù)說要配個圖才好看