在網(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ù)說要配個圖才好看
Paste_Image.png