Is it possible when using OkHttp to throttle the bandwidth? (possibly using a network interceptor).
You can make it work in two ways:
Using OkHttp the best way is Interceptor. There are also a few simple steps:
override fun source(): BufferedSource
needs to return the BandwidthSource's buffer.Example of BandwidthSource:
class BandwidthSource(
source: Source,
private val bandwidthLimit: Int
) : ForwardingSource(source) {
private var time = getSeconds()
override fun read(sink: Buffer, byteCount: Long): Long {
val read = super.read(sink, byteCount)
throttle(read)
return read
}
private fun throttle(byteCount: Long) {
val bitsCount = byteCount * BITS_IN_BYTE
val currentTime = getSeconds()
val timeDiff = currentTime - time
if (timeDiff == 0L) {
return
}
val kbps = bitsCount / timeDiff
if (kbps > bandwidthLimit) {
val times = (kbps / bandwidthLimit)
if (times > 0) {
runBlocking { delay(TimeUnit.SECONDS.toMillis(times)) }
}
}
time = currentTime
}
private fun getSeconds(): Long {
return TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With