This commit is contained in:
Horis 2023-06-28 11:59:29 +08:00
parent def2b03360
commit 3e7ce89959
3 changed files with 47 additions and 1 deletions

View File

@ -9,6 +9,8 @@ import okhttp3.*
import java.net.InetSocketAddress
import java.net.Proxy
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ThreadFactory
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
private val proxyClientCache: ConcurrentHashMap<String, OkHttpClient> by lazy {
@ -56,6 +58,7 @@ val okHttpClient: OkHttpClient by lazy {
.connectionSpecs(specs)
.followRedirects(true)
.followSslRedirects(true)
.addInterceptor(OkHttpExceptionInterceptor)
.addInterceptor(Interceptor { chain ->
val request = chain.request()
val builder = request.newBuilder()
@ -93,7 +96,18 @@ val okHttpClient: OkHttpClient by lazy {
}
}
}
builder.build()
builder.build().apply {
val okHttpName =
OkHttpClient::class.java.name.removePrefix("okhttp3.").removeSuffix("Client")
val executor = dispatcher.executorService as ThreadPoolExecutor
val threadName = "$okHttpName Dispatcher"
executor.threadFactory = ThreadFactory { runnable ->
Thread(runnable, threadName).apply {
isDaemon = false
uncaughtExceptionHandler = OkhttpUncaughtExceptionHandler
}
}
}
}
/**

View File

@ -0,0 +1,21 @@
package io.legado.app.help.http
import io.legado.app.utils.asIOException
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
object OkHttpExceptionInterceptor : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
try {
return chain.proceed(chain.request())
} catch (e: IOException) {
throw e
} catch (e: Throwable) {
throw IOException(e)
}
}
}

View File

@ -0,0 +1,11 @@
package io.legado.app.help.http
import io.legado.app.constant.AppLog
object OkhttpUncaughtExceptionHandler : Thread.UncaughtExceptionHandler {
override fun uncaughtException(t: Thread, e: Throwable) {
AppLog.put("Okhttp Dispatcher中的线程执行出错\n${e.localizedMessage}", e)
}
}