Speed Up download time

我的未来我决定 提交于 2019-12-12 07:37:38

问题


I have 40 MB file in server and i am downloading my file using

HttpURLConnection c = (HttpURLConnection) u.openConnection();
 c.setRequestMethod("GET");
 c.setDoOutput(true);
 c.connect();
 FileOutputStream f = new FileOutputStream(new File("trips.xml"));


 InputStream in = c.getInputStream();

 byte[] buffer = new byte[1024];
 int len1 = 0;
 while ( (len1 = in.read(buffer)) != -1 ) {
  f.write(buffer,0, len1);

this code seems working fine but it is taking too long. is their any way I can make this process faster.

/minhaz


回答1:


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).




回答2:


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];



回答3:


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;
}


来源:https://stackoverflow.com/questions/3302993/speed-up-download-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!