From 7d98431dcb96f196332100b696df4754f87448b8 Mon Sep 17 00:00:00 2001 From: kunfei Date: Mon, 28 Oct 2019 17:07:41 +0800 Subject: [PATCH] up --- .../legado/app/help/http/EncodeConverter.kt | 3 +- .../io/legado/app/utils/UTF8BOMFighter.kt | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 app/src/main/java/io/legado/app/utils/UTF8BOMFighter.kt diff --git a/app/src/main/java/io/legado/app/help/http/EncodeConverter.kt b/app/src/main/java/io/legado/app/help/http/EncodeConverter.kt index b17f50ef8..9e0b5ff1f 100644 --- a/app/src/main/java/io/legado/app/help/http/EncodeConverter.kt +++ b/app/src/main/java/io/legado/app/help/http/EncodeConverter.kt @@ -1,5 +1,6 @@ package io.legado.app.help.http +import io.legado.app.utils.UTF8BOMFighter import okhttp3.ResponseBody import retrofit2.Converter import retrofit2.Retrofit @@ -14,7 +15,7 @@ class EncodeConverter(private val encode: String? = null) : Converter.Factory() retrofit: Retrofit? ): Converter? { return Converter { value -> - val responseBytes = value.bytes() + val responseBytes = UTF8BOMFighter.removeUTF8BOM(value.bytes()) encode?.let { return@Converter String(responseBytes, Charset.forName(encode)) } var charsetName: String? = null diff --git a/app/src/main/java/io/legado/app/utils/UTF8BOMFighter.kt b/app/src/main/java/io/legado/app/utils/UTF8BOMFighter.kt new file mode 100644 index 000000000..5ced93613 --- /dev/null +++ b/app/src/main/java/io/legado/app/utils/UTF8BOMFighter.kt @@ -0,0 +1,30 @@ +package io.legado.app.utils + +object UTF8BOMFighter { + private val UTF8_BOM_BYTES = byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte()) + + fun removeUTF8BOM(xmlText: String): String { + val bytes = xmlText.toByteArray() + val containsBOM = (bytes.size > 3 + && bytes[0] == UTF8_BOM_BYTES[0] + && bytes[1] == UTF8_BOM_BYTES[1] + && bytes[2] == UTF8_BOM_BYTES[2]) + if (containsBOM) { + return String(bytes, 3, bytes.size - 3) + } + return xmlText + } + + fun removeUTF8BOM(bytes: ByteArray): ByteArray { + val containsBOM = (bytes.size > 3 + && bytes[0] == UTF8_BOM_BYTES[0] + && bytes[1] == UTF8_BOM_BYTES[1] + && bytes[2] == UTF8_BOM_BYTES[2]) + if (containsBOM) { + val copy = ByteArray(bytes.size - 3) + System.arraycopy(bytes, 3, copy, 0, bytes.size - 3) + return copy + } + return bytes + } +} \ No newline at end of file