OkHttp的請求攔截器,實現請求攔截,列印日誌到logcat
阿新 • • 發佈:2019-02-18
首先定義一個類NetWorkInterceptor實現Interceptor
話不多說,直接粘程式碼:
使用非常簡單,需要在client中加入addInterceptor,請求資料一切照舊,不要忘記新增依賴public class NetWorkInterceptor implements Interceptor { public static String TAG = "NetWorkInterceptor"; @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); if (BuildConfig.DEBUG) { String methodName = request.method(); if (methodName.equalsIgnoreCase("GET")) { Log.i(TAG, "-url--" + methodName + "--" + request.url()); } else if (methodName.equalsIgnoreCase("POST")) { RequestBody mRequestBody = request.body(); if (mRequestBody != null) { String msg = "-url--" + methodName + "--" + request.url(); String content; if (msg.contains("uploadFile")) { content = "--上傳檔案內容--"; } else { content = getParam(mRequestBody); } Log.i(TAG, msg + content); } } } Response response = chain.proceed(request); return response; } /** * 讀取引數 * * @param requestBody * @return */ private String getParam(RequestBody requestBody) { Buffer buffer = new Buffer(); String logparm; try { requestBody.writeTo(buffer); logparm = buffer.readUtf8(); logparm = URLDecoder.decode(logparm, "utf-8"); } catch (IOException e) { e.printStackTrace(); return ""; } return logparm; } }
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new NetWorkInterceptor())
.build();
日誌如下:
原著:https://github.com/leafseelight/OkHttpInterceptor