Bladeren bron

日志记录器中请求参数默认使用URLEncode

drake 3 jaren geleden
bovenliggende
commit
36a417197b

+ 9 - 5
net/src/main/java/com/drake/net/interceptor/LogRecordInterceptor.kt

@@ -24,9 +24,9 @@ import okhttp3.Response
  * @property responseByteCount 响应日志输出字节数, -1 则为全部
  */
 open class LogRecordInterceptor(
-    private val enabled: Boolean,
-    private val requestByteCount: Long = 1024 * 1024,
-    private val responseByteCount: Long = 1024 * 1024 * 4
+    val enabled: Boolean,
+    val requestByteCount: Long = 1024 * 1024,
+    val responseByteCount: Long = 1024 * 1024 * 4
 ) : Interceptor {
 
     init {
@@ -74,10 +74,14 @@ open class LogRecordInterceptor(
     /**
      * 请求字符串
      */
-    protected open fun requestString(request: Request) = request.logString(requestByteCount)
+    protected open fun requestString(request: Request): String? {
+        return request.logString(requestByteCount)
+    }
 
     /**
      * 响应字符串
      */
-    protected open fun responseString(response: Response) = response.logString(responseByteCount)
+    protected open fun responseString(response: Response): String? {
+        return response.logString(responseByteCount)
+    }
 }

+ 14 - 6
net/src/main/java/com/drake/net/request/RequestExtension.kt

@@ -25,6 +25,7 @@ import okhttp.OkHttpUtils
 import okhttp3.FormBody
 import okhttp3.Headers
 import okhttp3.Request
+import java.net.URLDecoder
 import java.util.concurrent.ConcurrentLinkedQueue
 import kotlin.reflect.KType
 
@@ -366,12 +367,19 @@ fun Request.Builder.setConverter(converter: NetConverter) = apply {
 /**
  * 请求日志信息
  * 只会输出 application/x-www-form-urlencoded, application/json, text/`*` 的请求体类型日志
+ * @param urlDecode 是否进行 UTF-8 URLDecode
  */
-fun Request.logString(byteCount: Long = 1024 * 1024): String? {
+fun Request.logString(byteCount: Long = 1024 * 1024, urlDecode: Boolean = true): String? {
     val mediaType = body?.contentType() ?: return null
-    return if (body is FormBody || mediaType.type == "text" || mediaType.subtype == "json") {
-        body?.peekString(byteCount)
-    } else {
-        "Not support this type $mediaType"
-    }
+    val bodyString =
+        if (body is FormBody || mediaType.type == "text" || mediaType.subtype == "json") {
+            body?.peekString(byteCount)
+        } else "Not support this type $mediaType"
+    return if (urlDecode) {
+        try {
+            URLDecoder.decode(bodyString, "UTF-8")
+        } catch (e: Exception) {
+            bodyString
+        }
+    } else bodyString
 }