代码之家  ›  专栏  ›  技术社区  ›  Ljdawson

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

  •  3
  • Ljdawson  · 技术社区  · 8 年前

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

    0 回复  |  直到 8 年前
        1
  •  2
  •   Alexandr Voronsky    6 年前

    您可以通过两种方式实现:

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

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

    1. 继承拦截器接口。
    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())
        }
    }
    
    推荐文章