18034727885
2026-05-13 03c43bb0d1abe7a22ce76bf903cc3c1e04648e44
common/src/main/java/com/xw/common/net/interceptor/LoggingInterceptor.kt
@@ -1,6 +1,7 @@
package com.xw.common.net.interceptor
import com.xw.common.utils.LogUtils
import okhttp3.Headers
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.MultipartBody
@@ -14,50 +15,77 @@
class LoggingInterceptor : Interceptor {
    val TAG = "zmc-Log"
    val TAG = "LoggingInterceptor"
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val startTime = System.currentTimeMillis()
        LogUtils.d("$TAG-${Thread.currentThread().id}", "head " + request.headers)
        LogUtils.d("$TAG-${Thread.currentThread().id}", "----------Start----------------")
        if (request.method.compareTo("get", true) == 0 || request.method.compareTo("delete", true) == 0) {
            LogUtils.d("$TAG-${Thread.currentThread().id}", "| " + URLDecoder.decode(request.toString(), "UTF-8"))
        } else {
            val requestInfo = "Request{method=${request.method}, url=${request.url}, head=${request.headers}}"
            LogUtils.d("$TAG-${Thread.currentThread().id}", "| $requestInfo")
            try {
                val jsonInfo = "RequestParams:" + URLDecoder.decode(bodyToString(request), "UTF-8")
                LogUtils.d("$TAG-${Thread.currentThread().id}", "| $jsonInfo")
            } catch (e: Exception) {
                LogUtils.e("$TAG-${Thread.currentThread().id}", "| " + "RequestParams:" + bodyToString(request))
                LogUtils.e("$TAG-${Thread.currentThread().id}", "| " + "error:" + e.message)
            }
        }
        val response: Response
        try {
            response = chain.proceed(request)
        } catch (e: IOException) {
            LogUtils.d(TAG, "----------Start----------------")
            printRequest(request)
            val endTime = System.currentTimeMillis()
            val duration = endTime - startTime
            LogUtils.e("$TAG-${Thread.currentThread().id}", "| Network Error: ${e.javaClass.simpleName}: ${e.message}")
            LogUtils.e("$TAG-${Thread.currentThread().id}", "----------End(Error):" + duration + "毫秒----------")
            e.printStackTrace()
            LogUtils.e(TAG, "----------End(Error):" + duration + "毫秒----------")
            throw e // 重新抛出,让上层处理
        }
        LogUtils.d(TAG, "----------Start----------------")
        printRequest(request)
        val endTime = System.currentTimeMillis()
        val bodyString = response.body?.string() ?: ""
        LogUtils.d("$TAG-${Thread.currentThread().id}", "| Response:$bodyString")
        LogUtils.d(TAG, "response=$bodyString")
        printHeader("responseHeaders=", response.headers)
        val duration = endTime - startTime
        LogUtils.d("$TAG-${Thread.currentThread().id}","----------End:" + duration + "毫秒----------")
        LogUtils.d(TAG, "----------End:" + duration + "毫秒----------")
        val newBody: ResponseBody = bodyString.toResponseBody(response.body?.contentType())
        return response.newBuilder()
            .body(newBody)
            .build()
    }
    //打印请求体
    private fun printRequest(request: Request) {
        LogUtils.d(TAG, "url=" + request.url)
        LogUtils.d(TAG, "method=" + request.method)
        printHeader("headers=", request.headers)
        if (request.method.compareTo("get", true) == 0 || request.method.compareTo(
                "delete",
                true
            ) == 0
        ) {
            val params = request.url.let { url ->
                url.queryParameterNames.associateWith {
                    url.queryParameter(it)
                }
            }.map { "${it.key}=${it.value}" }.joinToString("&")
            LogUtils.d(TAG, "params=${params}")
        } else {
            try {
                LogUtils.d(TAG, "params=${URLDecoder.decode(bodyToString(request), "UTF-8")}")
            } catch (e: Exception) {
                e.printStackTrace()
                LogUtils.e(TAG, "params=${bodyToString(request)}")
            }
        }
    }
    private fun printHeader(prefix: String, headers: Headers) {
        LogUtils.d(TAG, prefix + buildString {
            for (i in 0 until headers.size) {
                val name = headers.name(i)
                val value = headers.value(i)
                append(name)
                append(": ")
                append(value)
                append("\n")
            }
        })
    }
    private fun bodyToString(request: Request): String? {
@@ -79,8 +107,9 @@
                copy.body!!.writeTo(buffer)
            }
            buffer.readUtf8()
        } catch (e: IOException) {
            "did not work"
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }