Skip to content

Instantly share code, notes, and snippets.

@Haoxiqiang
Created May 6, 2022 03:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Haoxiqiang/90d496b5a60aa554e2fbb43e4505caa1 to your computer and use it in GitHub Desktop.
Save Haoxiqiang/90d496b5a60aa554e2fbb43e4505caa1 to your computer and use it in GitHub Desktop.
Ktor support request with gzip on the Android platform.
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