1. 程式人生 > >OkHttp的請求攔截器,實現請求攔截,列印日誌到logcat

OkHttp的請求攔截器,實現請求攔截,列印日誌到logcat

首先定義一個類NetWorkInterceptor實現Interceptor

話不多說,直接粘程式碼:

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;
    }
}
使用非常簡單,需要在client中加入addInterceptor,請求資料一切照舊,不要忘記新增依賴
OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new NetWorkInterceptor())
                .build();

日誌如下:


原著:https://github.com/leafseelight/OkHttpInterceptor