Skip to content

Commit

Permalink
优化
Browse files Browse the repository at this point in the history
  • Loading branch information
821938089 committed Dec 29, 2023
1 parent 2f29c11 commit 73dc85e
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
31 changes: 31 additions & 0 deletions app/src/main/java/io/legado/app/help/http/HttpHelper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import io.legado.app.constant.AppConst
import io.legado.app.help.CacheManager
import io.legado.app.help.config.AppConfig
import io.legado.app.help.http.CookieManager.cookieJarHeader
import io.legado.app.utils.GzipSourceCompat
import io.legado.app.utils.NetworkUtils
import okhttp3.ConnectionSpec
import okhttp3.Cookie
Expand All @@ -12,6 +13,9 @@ import okhttp3.Credentials
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.internal.http.RealResponseBody
import okhttp3.internal.http.promisesBody
import okio.buffer
import java.net.InetSocketAddress
import java.net.Proxy
import java.util.concurrent.ConcurrentHashMap
Expand Down Expand Up @@ -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 {
val okHttpName =
OkHttpClient::class.java.name.removePrefix("okhttp3.").removeSuffix("Client")
Expand Down
26 changes: 26 additions & 0 deletions app/src/main/java/io/legado/app/utils/GzipSourceCompat.kt
Original file line number Diff line number Diff line change
@@ -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()

}

0 comments on commit 73dc85e

Please sign in to comment.