18034727885
2026-04-27 3a4c1bbb2cf4fb1cdda8a5061b0674f30e7456b4
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package com.example.smart.reqeust.interceptor
 
import android.annotation.SuppressLint
import android.util.Log
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import okio.Buffer
import retrofit2.Invocation
import retrofit2.http.Streaming
import java.io.IOException
import java.net.URLDecoder
import java.nio.charset.StandardCharsets
 
class LoggingInterceptorZmc : Interceptor {
 
    @SuppressLint("LogNotTimber")
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
 
        val startTime = System.currentTimeMillis()
        Log.d(TAG + "-" + Thread.currentThread().id, "----------Start----------------")
        if ("GET".equals(request.method, ignoreCase = true) || "DELETE".equals(
                request.method,
                ignoreCase = true
            )
        ) {
            Log.d(
                TAG + "-" + Thread.currentThread().id,
                "| " + URLDecoder.decode(request.toString(), StandardCharsets.UTF_8.name())
            )
        } else {
            val requestInfo =
                "Request{method=" + request.method + ", url=" + request.url + ", head=" + request.headers + "}"
            Log.d(TAG + "-" + Thread.currentThread().id, "| $requestInfo")
            try {
                val jsonInfo = "RequestParams:" + URLDecoder.decode(
                    bodyToString(request),
                    StandardCharsets.UTF_8.name()
                )
                Log.d(TAG + "-" + Thread.currentThread().id, "| $jsonInfo")
            } catch (e: Exception) {
                Log.e(
                    TAG + "-" + Thread.currentThread().id,
                    "| " + "RequestParams:" + bodyToString(request)
                )
                Log.e(TAG + "-" + Thread.currentThread().id, "| " + "error:" + e.message)
            }
        }
 
        val response: Response = chain.proceed(request)
        val endTime = System.currentTimeMillis()
 
        val duration = endTime - startTime
        if (!request.containMethodAnnotation(Streaming::class.java)) {
            val bodyString = response.body!!.string()
            Log.d(TAG + "-" + Thread.currentThread().id, "| Response:$bodyString")
            Log.d(
                TAG + "-" + Thread.currentThread().id,
                "----------End:" + duration + "毫秒----------"
            )
            val newBody = ResponseBody.create(response.body!!.contentType(), bodyString)
 
            return response.newBuilder()
                .body(newBody)
                .build()
        } else {
            Log.d(TAG + "-" + Thread.currentThread().id, "| Response:{数据流}")
            Log.d(
                TAG + "-" + Thread.currentThread().id,
                "----------End:" + duration + "毫秒----------"
            )
            return response.newBuilder()
                .body(response.body!!)
                .build()
        }
    }
 
    private fun bodyToString(request: Request): String {
        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)
            }
            return buffer.readUtf8()
        } catch (e: IOException) {
            return "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("multipart/form-data")
        }
        return false
    }
 
    /**
     * 返回某个Retrofit定义在方法上的注解,例如[POST],[GET]
     */
    fun <T : Annotation> Request.getMethodAnnotation(annotationClass: Class<T>): T? {
        return tag(Invocation::class.java)?.method()?.getAnnotation(annotationClass)
    }
 
 
    fun <T : Annotation> Request.containMethodAnnotation(annotationClass: Class<T>): Boolean {
        return getMethodAnnotation(annotationClass) != null
    }
 
    companion object {
        private const val TAG = "zmc-Log"
    }
}