18034727885
2026-04-14 370014cbb9ec1ef64e7e42bb4f9a12671461d8e4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.xw.common.net.interceptor
 
import com.xw.common.utils.LogUtils
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import okio.Buffer
import java.io.IOException
import java.net.URLDecoder
 
class LoggingInterceptor : Interceptor {
 
    val TAG = "zmc-Log"
 
    @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) {
            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 + "毫秒----------")
            throw e // 重新抛出,让上层处理
        }
        val endTime = System.currentTimeMillis()
 
        val bodyString = response.body?.string() ?: ""
        LogUtils.d("$TAG-${Thread.currentThread().id}", "| Response:$bodyString")
        val duration = endTime - startTime
        LogUtils.d("$TAG-${Thread.currentThread().id}","----------End:" + duration + "毫秒----------")
 
        val newBody: ResponseBody = bodyString.toResponseBody(response.body?.contentType())
        return response.newBuilder()
            .body(newBody)
            .build()
    }
 
    private fun bodyToString(request: Request): String? {
        return try {
            val copy = request.newBuilder().build()
            val buffer = Buffer()
            if (copy.body is MultipartBody) {
                val multipartBody = copy.body as MultipartBody
                for (i in 0 until multipartBody.size) {
                    val part = multipartBody.part(i)
                    val mediaType = part.body.contentType()
                    if (!isFilePart(mediaType)) {
                        part.body.writeTo(buffer)
                    } else {
                        buffer.writeUtf8("file params Content-Type: $mediaType\n")
                    }
                }
            } else {
                copy.body!!.writeTo(buffer)
            }
            buffer.readUtf8()
        } catch (e: IOException) {
            "did not work"
        }
    }
 
 
    // 是否为文件
    fun isFilePart(mediaType: MediaType?): Boolean {
        if (mediaType != null) {
            val type = mediaType.toString()
            return type.startsWith("audio/") || type.startsWith("text/plain") || type.startsWith("image/jpg") || type.startsWith(
                "application/json"
            )
        }
        return false
    }
 
}