Ljd*_*son 7 android android-networking okhttp okhttp3
使用 OkHttp 来限制带宽时是否可能?(可能使用网络拦截器)。
小智 4
您可以通过两种方式使其发挥作用:
使用OkHttp最好的方法是Interceptor。还有几个简单的步骤:
override fun source(): BufferedSource需要返回 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())
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
497 次 |
| 最近记录: |