使用 OkHttp 时是否可以限制带宽?

Ljd*_*son 7 android android-networking okhttp okhttp3

使用 OkHttp 来限制带宽时是否可能?(可能使用网络拦截器)。

小智 4

您可以通过两种方式使其发挥作用:

  1. 手动发送请求并读取流,并在读取时进行节流。
  2. 添加拦截器。

使用OkHttp最好的方法是Interceptor。还有几个简单的步骤:

  1. 继承Interceptor接口。
  2. 继承ResponseBody类。
  3. 在自定义 ResponceBody 中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)

  • 很好的答案。顺便说一句,Okio 现在内置了类似的功能,因此您无需编写太多代码即可实现结果。https://square.github.io/okio/2.x/okio/okio/-throttler/ (2认同)