optimize response handling

This commit is contained in:
Minecon724 2024-08-08 13:14:18 +02:00
parent 3e1631908a
commit 9c1741f769
Signed by: Minecon724
GPG key ID: 3CCC4D267742C8E8

View file

@ -25,7 +25,8 @@ open class StringUrlRequestCallback(
}
override fun onResponseStarted(request: UrlRequest?, info: UrlResponseInfo?) {
request?.read(ByteBuffer.allocateDirect(102400))
val size = info?.allHeaders?.get("content-length")?.get(0)?.toIntOrNull()
request?.read(ByteBuffer.allocateDirect(size ?: 100000))
}
override fun onReadCompleted(
@ -36,13 +37,19 @@ open class StringUrlRequestCallback(
byteBuffer?.clear()
request?.read(byteBuffer)
stringResponse.append(Charsets.UTF_8.newDecoder().onUnmappableCharacter(CodingErrorAction.IGNORE).decode(byteBuffer))
stringResponse.append(
Charsets.UTF_8.newDecoder()
.onUnmappableCharacter(CodingErrorAction.IGNORE)
.decode(byteBuffer)
)
}
override fun onSucceeded(request: UrlRequest?, info: UrlResponseInfo?) {
if (info != null) {
val body = stringResponse.toString()
val statusCode = info.httpStatusCode
println(info.httpStatusCode.toString() + ": " + stringResponse.substring(0, stringResponse.length))
println(info.allHeaders.toString())
if (statusCode == 200) {
try {
@ -52,7 +59,7 @@ open class StringUrlRequestCallback(
}
} else if (statusCode >= 500) {
onFailure(ServerError(statusCode, body))
} else if (statusCode == 403) {
} else if (statusCode == 401) {
onFailure(UnauthorizedException(body))
} else {
onFailure(ClientException(body))