From aec33ee3e1d377342fb9294bf53b0523e746067c Mon Sep 17 00:00:00 2001 From: dongliang Date: Mon, 27 Apr 2026 20:47:53 +0930 Subject: [PATCH] =?UTF-8?q?fix:=20UnbindInterceptor=20=E6=94=B9=E7=94=A8?= =?UTF-8?q?=20peekBody=20=E9=98=B2=E6=AD=A2=E6=B6=88=E8=B4=B9=E5=93=8D?= =?UTF-8?q?=E5=BA=94=E4=BD=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit source.request() 在空body/非JSON响应时会导致后续Gson解析失败。 改用 peekBody(1024) 安全读取副本。 Co-Authored-By: Claude Opus 4.6 (1M context) --- .../xiaoqu/watch/network/UnbindInterceptor.kt | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/com/xiaoqu/watch/network/UnbindInterceptor.kt b/app/src/main/java/com/xiaoqu/watch/network/UnbindInterceptor.kt index c2743da..1b3aa62 100644 --- a/app/src/main/java/com/xiaoqu/watch/network/UnbindInterceptor.kt +++ b/app/src/main/java/com/xiaoqu/watch/network/UnbindInterceptor.kt @@ -14,6 +14,7 @@ import javax.inject.Singleton /** * 解绑拦截器 * 检测 API 返回 code=104 时,自动清除用户数据并发送解绑事件 + * 使用 peekBody 安全读取响应体,不影响后续解析 */ @Singleton class UnbindInterceptor @Inject constructor( @@ -25,23 +26,25 @@ class UnbindInterceptor @Inject constructor( override fun intercept(chain: Interceptor.Chain): Response { val response = chain.proceed(chain.request()) + // 只处理成功的 HTTP 响应 if (response.isSuccessful) { try { - // 窥视响应体(不消耗) - val source = response.body?.source() ?: return response - source.request(Long.MAX_VALUE) - val buffer = source.buffer.clone() - val json = buffer.readUtf8() + // peekBody 安全读取副本,不消耗原始 body + val peekBody = response.peekBody(1024) + val json = peekBody.string() - val apiResponse = gson.fromJson(json, ApiResponse::class.java) - if (apiResponse?.isUnbound == true) { - Timber.w("收到 code=104,执行自动解绑") - userPrefs.clear() - runBlocking { - eventBus.emit(AppEvent.DeviceUnbound) + if (json.isNotEmpty()) { + val apiResponse = gson.fromJson(json, ApiResponse::class.java) + if (apiResponse?.isUnbound == true) { + Timber.w("收到 code=104,执行自动解绑") + userPrefs.clear() + runBlocking { + eventBus.emit(AppEvent.DeviceUnbound) + } } } } catch (e: Exception) { + // 解析异常不影响正常请求 Timber.w(e, "解绑检测异常") } }