使用OkHttp来限制带宽是否可行? (可能使用网络拦截器。)
答案 0 :(得分:2)
您可以通过两种方式使其工作:
使用OkHttp最好的方法是拦截器。还有一些简单的步骤:
override fun source(): BufferedSource
中,需要返回BandwidthSource的缓冲区。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())
}
}