This commit is contained in:
Horis
2023-12-29 16:54:57 +08:00
parent 30a85f5428
commit 8b1c2f3f4f
2 changed files with 57 additions and 0 deletions
@@ -4,6 +4,7 @@ import io.legado.app.constant.AppConst
import io.legado.app.help.CacheManager import io.legado.app.help.CacheManager
import io.legado.app.help.config.AppConfig import io.legado.app.help.config.AppConfig
import io.legado.app.help.http.CookieManager.cookieJarHeader import io.legado.app.help.http.CookieManager.cookieJarHeader
import io.legado.app.utils.GzipSourceCompat
import io.legado.app.utils.NetworkUtils import io.legado.app.utils.NetworkUtils
import okhttp3.ConnectionSpec import okhttp3.ConnectionSpec
import okhttp3.Cookie import okhttp3.Cookie
@@ -12,6 +13,9 @@ import okhttp3.Credentials
import okhttp3.HttpUrl import okhttp3.HttpUrl
import okhttp3.Interceptor import okhttp3.Interceptor
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
import okhttp3.internal.http.RealResponseBody
import okhttp3.internal.http.promisesBody
import okio.buffer
import java.net.InetSocketAddress import java.net.InetSocketAddress
import java.net.Proxy import java.net.Proxy
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
@@ -102,6 +106,33 @@ val okHttpClient: OkHttpClient by lazy {
} }
} }
} }
builder.addInterceptor { chain ->
val request = chain.request()
val requestBuilder = request.newBuilder()
requestBuilder.header("Accept-Encoding", "gzip")
val response = chain.proceed(requestBuilder.build())
val responseBody = response.body
if ("gzip".equals(response.header("Content-Encoding"), ignoreCase = true)
&& response.promisesBody() && responseBody != null
) {
val responseBuilder = response.newBuilder()
val gzipSource = GzipSourceCompat(responseBody.source())
val strippedHeaders = response.headers.newBuilder()
.removeAll("Content-Encoding")
.removeAll("Content-Length")
.build()
responseBuilder.run {
headers(strippedHeaders)
val contentType = response.header("Content-Type")
body(RealResponseBody(contentType, -1L, gzipSource.buffer()))
build()
}
} else {
response
}
}
builder.build().apply { builder.build().apply {
val okHttpName = val okHttpName =
OkHttpClient::class.java.name.removePrefix("okhttp3.").removeSuffix("Client") OkHttpClient::class.java.name.removePrefix("okhttp3.").removeSuffix("Client")
@@ -0,0 +1,26 @@
package io.legado.app.utils
import okio.Buffer
import okio.EOFException
import okio.GzipSource
import okio.Source
class GzipSourceCompat(source: Source) : Source {
private val delegate = GzipSource(source)
override fun close() = delegate.close()
override fun read(sink: Buffer, byteCount: Long): Long {
try {
return delegate.read(sink, byteCount)
} catch (e: EOFException) {
if (e.message == "source exhausted prematurely") {
return -1
}
throw e
}
}
override fun timeout() = delegate.timeout()
}