|
|
@@ -16,9 +16,11 @@ import okhttp3.RequestBody.Companion.asRequestBody
|
|
|
import okhttp3.RequestBody.Companion.toRequestBody
|
|
|
import okhttp3.Response
|
|
|
import okhttp3.ResponseBody
|
|
|
+import okhttp3.internal.http.RealResponseBody
|
|
|
+import okio.buffer
|
|
|
+import okio.source
|
|
|
import java.io.File
|
|
|
import java.io.IOException
|
|
|
-import java.io.InputStream
|
|
|
import java.nio.charset.Charset
|
|
|
import java.util.zip.ZipInputStream
|
|
|
import kotlin.coroutines.resume
|
|
|
@@ -77,36 +79,37 @@ suspend fun Call.await(): Response = suspendCancellableCoroutine { block ->
|
|
|
}
|
|
|
|
|
|
fun ResponseBody.text(encode: String? = null): String {
|
|
|
- return unCompress {
|
|
|
- val responseBytes = Utf8BomUtils.removeUTF8BOM(it.readBytes())
|
|
|
- var charsetName: String? = encode
|
|
|
+ val responseBytes = Utf8BomUtils.removeUTF8BOM(bytes())
|
|
|
+ var charsetName: String? = encode
|
|
|
|
|
|
- charsetName?.let {
|
|
|
- return@unCompress String(responseBytes, Charset.forName(charsetName))
|
|
|
- }
|
|
|
-
|
|
|
- //根据http头判断
|
|
|
- contentType()?.charset()?.let { charset ->
|
|
|
- return@unCompress String(responseBytes, charset)
|
|
|
- }
|
|
|
+ charsetName?.let {
|
|
|
+ return String(responseBytes, Charset.forName(charsetName))
|
|
|
+ }
|
|
|
|
|
|
- //根据内容判断
|
|
|
- charsetName = EncodingDetect.getHtmlEncode(responseBytes)
|
|
|
- return@unCompress String(responseBytes, Charset.forName(charsetName))
|
|
|
+ //根据http头判断
|
|
|
+ contentType()?.charset()?.let { charset ->
|
|
|
+ return String(responseBytes, charset)
|
|
|
}
|
|
|
+
|
|
|
+ //根据内容判断
|
|
|
+ charsetName = EncodingDetect.getHtmlEncode(responseBytes)
|
|
|
+ return String(responseBytes, Charset.forName(charsetName))
|
|
|
}
|
|
|
|
|
|
-fun <T> ResponseBody.unCompress(success: (inputStream: InputStream) -> T): T {
|
|
|
- return if (contentType() == "application/zip".toMediaType()) {
|
|
|
- byteStream().use { byteStream ->
|
|
|
- ZipInputStream(byteStream).use {
|
|
|
- it.nextEntry
|
|
|
- success.invoke(it)
|
|
|
- }
|
|
|
- }
|
|
|
- } else {
|
|
|
- byteStream().use(success)
|
|
|
+fun ResponseBody.decompressed(): ResponseBody {
|
|
|
+ val contentType = contentType()?.toString()
|
|
|
+ if (contentType != "application/zip") {
|
|
|
+ return this
|
|
|
}
|
|
|
+ val source = ZipInputStream(byteStream()).apply {
|
|
|
+ try {
|
|
|
+ nextEntry
|
|
|
+ } catch (e: Exception) {
|
|
|
+ close()
|
|
|
+ throw e
|
|
|
+ }
|
|
|
+ }.source().buffer()
|
|
|
+ return RealResponseBody(contentType, contentLength(), source)
|
|
|
}
|
|
|
|
|
|
fun Request.Builder.addHeaders(headers: Map<String, String>) {
|