Speed Up download time

喜欢而已 提交于 2019-12-03 08:21:16

This very ugly hack which might give you a faster download time, or maybe it doesn't, you'll have to test it under your conditions:

Start several parallel connections (in separate threads?), and each one should download a different chunk of data (using HTTP 1.1 Range header). Depending on many things like if there's a full moon, or the sun is out or the roses are blooming you might get better results because it will saturate your link better than a single connection (to the expense of everyone else sharing your link, kinda like what BitTorrent does).

Use larger input buffer than 1 KB. The faster you empty buffer, the faster network stack can continue downloading. This should help:

byte[] buffer = new byte[50*1024];

I am having the same problem, came up with this code. Was faster than previous versions I have tried. I specify a buffer size greater than the file I am going to down load. Hope it helps.

    public String load(String url, int bufferSize){

    try {
        URL myURL = new URL(url);
        URLConnection ucon = myURL.openConnection();
        ucon.setRequestProperty("Connection", "keep-alive");
        InputStream inputStream = ucon.getInputStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        ByteArrayBuffer byteArrayBuffer = new ByteArrayBuffer(bufferSize);
        byte[] buf = new byte[bufferSize];
        int read;
        do {
            read = bufferedInputStream.read(buf, 0, buf.length);
            if (read > 0)
                byteArrayBuffer.append(buf, 0, read);
        } while (read >= 0);
        return new String(byteArrayBuffer.toByteArray());
    } catch (Exception e) {
        Log.i("Error", e.toString());
    }
    return null;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!