fix(android): 修正下载URL解析和CookieManager线程
- 解析相对下载地址时使用 HOME_URL 域名根路径,避免把当前对话路径拼进URL - CookieManager.getCookie 在主线程调用后再传入IO线程
This commit is contained in:
parent
6a5ba2d95e
commit
86eef988dc
@ -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 {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user