Created
May 6, 2022 03:38
-
-
Save Haoxiqiang/90d496b5a60aa554e2fbb43e4505caa1 to your computer and use it in GitHub Desktop.
Ktor support request with gzip on the Android platform.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ktorHttpClient.post("xxxx") { | |
tryCompress(this, json) | |
} | |
private fun tryCompress(httpRequestBuilder: HttpRequestBuilder, json: JSONObject) { | |
val stringBody = tryCreateRequestBody(json = json) | |
if (stringBody.length > 4096) { | |
httpRequestBuilder.body = stringBody.gzipCompress() | |
httpRequestBuilder.headers[HttpHeaders.ContentEncoding] = "gzip" | |
} else { | |
httpRequestBuilder.body = stringBody | |
} | |
httpRequestBuilder.body = stringBody | |
} | |
fun String.gzipCompress(): ByteArray { | |
val byteArrayOutputStream = ByteArrayOutputStream() | |
return byteArrayOutputStream.use { stream -> | |
GZIPOutputStream(stream).bufferedWriter(Charsets.UTF_8) | |
.use { writer -> writer.write(this) } | |
stream.toByteArray() | |
} | |
} | |
fun ByteArray.gzipDecompress(): String { | |
val byteArrayInputStream = ByteArrayInputStream(this) | |
byteArrayInputStream.use { stream -> | |
GZIPInputStream(stream).bufferedReader(Charsets.UTF_8) | |
.use { reader -> return reader.readText() } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment