diff --git a/android-webview-app/app/src/main/java/com/cyjai/agent/MainActivity.kt b/android-webview-app/app/src/main/java/com/cyjai/agent/MainActivity.kt index 722b384..5c4733e 100644 --- a/android-webview-app/app/src/main/java/com/cyjai/agent/MainActivity.kt +++ b/android-webview-app/app/src/main/java/com/cyjai/agent/MainActivity.kt @@ -544,7 +544,12 @@ class MainActivity : AppCompatActivity() { Toast.makeText(this@MainActivity, "正在下载:$fileName", Toast.LENGTH_SHORT).show() } - val downloadedFile = downloadFileToAppDir(absoluteUrl, fileName) + // CookieManager 必须在主线程访问 + val cookie = withContext(Dispatchers.Main) { + CookieManager.getInstance().getCookie(absoluteUrl) + } + + val downloadedFile = downloadFileToAppDir(absoluteUrl, fileName, cookie) withContext(Dispatchers.Main) { shareDownloadedFile(downloadedFile) @@ -563,13 +568,13 @@ class MainActivity : AppCompatActivity() { } } - private fun downloadFileToAppDir(urlString: String, preferredName: String): File { + private fun downloadFileToAppDir(urlString: String, preferredName: String, cookie: String?): File { val dir = File(filesDir, "downloads").apply { mkdirs() } val connection = URL(urlString).openConnection() as HttpURLConnection connection.connectTimeout = 30000 connection.readTimeout = 30000 connection.instanceFollowRedirects = true - connection.setRequestProperty("Cookie", CookieManager.getInstance().getCookie(urlString) ?: "") + connection.setRequestProperty("Cookie", cookie ?: "") connection.connect() val finalUrl = connection.url.toString() @@ -621,12 +626,10 @@ class MainActivity : AppCompatActivity() { private fun resolveAbsoluteUrl(rawUrl: String): String { if (rawUrl.startsWith("http://") || rawUrl.startsWith("https://")) return rawUrl - val base = webView.url?.takeIf { it.startsWith("http://") || it.startsWith("https://") } ?: HOME_URL - return if (rawUrl.startsWith("/")) { - base.substringBefore("?").trimEnd('/') + rawUrl - } else { - base.trimEnd('/') + "/" + rawUrl - } + // API 始终位于域名根路径,不能拿当前 WebView URL(可能包含对话路径 /conv_id)作为 base, + // 否则会把 /api/download/file 拼到对话路径后面,导致 404。 + val base = HOME_URL.trimEnd('/') + return if (rawUrl.startsWith("/")) "$base$rawUrl" else "$base/$rawUrl" } inner class ThemeBridge {