在網絡請求的時候我們一般會打印日誌,包含請求地址、請求參數、返回結果、請求耗時等。
在之前的操作中,可能會,在Request執行的時候打印一下,Response返回結果的時候打印一下。那麼這樣在如果同時多個請求的情況下就會產生混亂,日誌裏會出現並列多個請求,並列多個結果。那麼使用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是兩種常見的請求方式,網上很多文章只是說明了打印請求地址,在Get請求時候這個參數會拼接在請求地址後面,而Post請求的參數是在請求體裏面的,因此必需要先獲取到請求體然後遍歷,拿到請求參數。因此上面代碼中的這部分是爲了打印Post請求參數而來。
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();
據說要配個圖纔好看