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