1

我用来AndroidHttpClient从互联网上下载视频。AndroidHttpClient有一些方法可以提高下载速度,但我想知道如何使用or来降低下载速度HttpURLConnection?是否有针对该或某些解决方案的接口或配置?

** * ** * ** * ** * ** * *更新* ** * ** * ** * ** * ** * *

做了一些测试,发现正如 Matthew Franglen 建议的那样,Thread.sleep(value)可以是一个解决方案。主要的魔法是确定valuefor线程进入睡眠状态。测试结果如下

no thread sleep
11-06 20:05:14.510: D/DownloadThread(6197): Current speed = 1793978

sleep 0.001s
11-06 20:02:28.433: D/DownloadThread(5290): Current speed = 339670

sleep 0.062
11-06 20:00:25.382: D/DownloadThread(4410): Current speed = 65036

sleep 0.125s
11-06 19:58:56.197: D/DownloadThread(3401): Current speed = 33383

sleep 0.25s
11-06 19:57:21.165: D/DownloadThread(2396): Current speed = 15877

sleep 0.5s
11-06 19:55:16.462: D/DownloadThread(1253): Current speed = 8061

sleep 1s
11-06 19:53:18.917: D/DownloadThread(31743): Current speed = 3979

测试显示,如果睡眠一秒,下载量会急剧下降到 1/450 左右!

虽然这取决于下载循环中所做的操作类型,并且取决于环境。这是具体情况下的实验结论

4

1 回答 1

1

降低下载速度非常简单。只需更慢地从 InputStream 中读取:

public byte[] rateLimitedDownload(InputStream in, int bytesPerSecond) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buffer = new byte[bytesPerSecond];
    int read;

    while ((read = in.read(buffer)) != -1) {
        out.write(buffer, 0, read);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // nothing
        }
    }
    return out.toByteArray();
}

这段代码并不完美 - 没有考虑实际从 in 读取所花费的任何时间,并且读取次数可能少于预期。它应该给你一个想法。

于 2013-11-06T09:58:01.420 回答