OkHttp自定義攔截器打印post請求報文

OkHttp自定義攔截器打印post請求報文

背景:
我們直接使用打印request.toString或request.body時打印的攜帶請求頭、content-type的全部請求信息,實際開發中我們可能只需要打印真實上送報文。
有以上需求的可以通過自定義日誌攔截器方法處理:

第一步:自定義日誌攔截器 LoggingInterceptor.java

public class LoggingInterceptor implements Interceptor {

    Context context;

    public LoggingInterceptor(Context mcontext) {

        this.context = mcontext;
    }

    public LoggingInterceptor() {
    }

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();

        //處理請求報文打印
        LogUtils.d("request.toString()== " + request.toString());
        String method = request.method();
        

	//重點部分----------針對post請求做處理-----------------------
		if ("POST".equals(method)) {//post請求需要拼接
            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());
                LogUtils.i("請求報文: RequestParams:{" + sb.toString() + "}");
            }
        } else {//get請求直接打印url
            LogUtils.i("request params==" + request.url() + "\n 參數==" + request.body().toString());
        }


        long startTime = System.currentTimeMillis();
        Response response = chain.proceed(request);
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        LogUtils.d("----------END---------" + duration + "毫秒----");

        //處理響應報文打印
        MediaType contentType = null;
        String bodyString = null;
        if (response.body() != null) {
            contentType = response.body().contentType();
            bodyString = JsonTransfer(response.body().string());
        }
        LogUtils.d("response: " + response.code() + "\n" + bodyString);
        if (response.body() != null) {// 深坑!打印body後原ResponseBody會被清空,需要重新設置body
            ResponseBody body = ResponseBody.create(contentType, bodyString);
            return response.newBuilder().body(body).build();
        } else {
            return response;
        }
    }
}

第二步:在初始化okHttpClientBuilder 時添加攔截器


    public static OkHttpClient getOkHttpClient(Context context) {
        mContext = context;

        OkHttpClient okHttpClient = new OkHttpClient();
        OkHttpClient.Builder okHttpClientBuilder = okHttpClient.newBuilder()
                .sslSocketFactory(getSslSocketFactory())
//                .hostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                })
                .addInterceptor(new LoggingInterceptor(mContext))
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .connectTimeout(20, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true);
        return okHttpClientBuilder.build();
    }

發佈了64 篇原創文章 · 獲贊 38 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章