Okhttp設置請求日志過濾器,支持打印Post請求參數

在網絡請求的時候我們一般會打印日志,包含請求地址、請求參數、返回結果、請求耗時等。

在之前的操作中,可能會,在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();

據說要配個圖才好看


Paste_Image.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容