refactor(network): 优化网络请求日志记录功能
- 添加RequestBody导入以支持请求体读取 - 实现详细的请求日志记录函数logRequest - 添加请求体转字符串的辅助函数bodyToString - 替换简单的URL日志为完整的请求详情日志 - 包含请求方法、URL、请求头和请求体的完整信息 - 添加异常处理确保请求体读取失败时的稳定性
这个提交包含在:
父节点
63794d0fb8
当前提交
9e5f68c320
@ -7,6 +7,7 @@ import com.xuqm.base.extensions.log
|
||||
import com.xuqm.base.extensions.loge
|
||||
import okhttp3.Headers
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.Response
|
||||
import okio.Buffer
|
||||
import okio.BufferedSource
|
||||
@ -37,7 +38,7 @@ class HeaderInterceptor(val context: Context) : Interceptor {
|
||||
// context.getStringForPreferences(SHARE_UESR_TOKEN).loge()
|
||||
|
||||
val request = requestBuilder.build()
|
||||
"${request.url}(${request.method})".loge()
|
||||
logRequest(request)
|
||||
|
||||
val headers = request.headers
|
||||
|
||||
@ -79,6 +80,34 @@ class HeaderInterceptor(val context: Context) : Interceptor {
|
||||
return response
|
||||
}
|
||||
|
||||
private fun logRequest(request: okhttp3.Request) {
|
||||
val requestBodyText = request.body?.let { bodyToString(it) }.orEmpty()
|
||||
buildString {
|
||||
append("request: ")
|
||||
append(request.method)
|
||||
append(" ")
|
||||
append(request.url)
|
||||
append('\n')
|
||||
append("headers: ")
|
||||
append(request.headers)
|
||||
if (requestBodyText.isNotBlank()) {
|
||||
append('\n')
|
||||
append("body: ")
|
||||
append(requestBodyText)
|
||||
}
|
||||
}.loge()
|
||||
}
|
||||
|
||||
private fun bodyToString(requestBody: RequestBody): String {
|
||||
return runCatching {
|
||||
val buffer = Buffer()
|
||||
requestBody.writeTo(buffer)
|
||||
buffer.readString(UTF8)
|
||||
}.getOrElse {
|
||||
"unable to read request body: ${it.message}"
|
||||
}
|
||||
}
|
||||
|
||||
private fun bodyHasUnknownEncoding(headers: Headers): Boolean {
|
||||
val contentEncoding = headers["Content-Encoding"]
|
||||
return (contentEncoding != null && !contentEncoding.equals("identity", ignoreCase = true)
|
||||
@ -125,4 +154,4 @@ class HeaderInterceptor(val context: Context) : Interceptor {
|
||||
ignoreCase = true
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
正在加载...
在新工单中引用
屏蔽一个用户