Jonathan S.
Jonathan S.

Reputation: 1550

Fastest way to seek (skip) an inputstream with http protocol

I am making a download service of sorts, and it has the ability to resume a previous partial download. I am currently using the skip method like this

                long skipped = 0;
                while (skipped < track.getCacheFile().length()){
                    skipped += is.skip(track.getCacheFile().length()-skipped);

                }

I just did a test and it took about 57 seconds seconds to skip 45 mb in an inputstream. I am curious how certain native code does this, for instance, the mediaplayer can seek to any part of a remote stream instantaneously. I realize that I do not have access to the same libraries, but can I achieve something similar.

btw, that test was on wifi. It is obviously much slower on normal data networks.

Update: very simple (thanks to below)

if (track.getCacheFile().length() > 0){
    request.setHeader("Range","bytes="+track.getCacheFile().length()+"-");  
}

Upvotes: 2

Views: 1698

Answers (3)

radhoo
radhoo

Reputation: 2945

You can do it like this:

private InputStream getRemote(String url, long offset) {
    try {
        URLConnection cn = new URL( url ).openConnection();
        cn.setRequestProperty ("Range", "bytes="+offset+"-");
        cn.connect();
        length = cn.getContentLength();
        return cn.getInputStream();
    } catch (MalformedURLException e ) { e.printStackTrace();
    } catch (IOException e) { e.printStackTrace(); }

    return null;
}

Then when you need to skip, you actually do a reconnect via HTTP to the new offset. Works quick and reliable, much better than using the inputstream's skip.

Upvotes: 1

Yahel
Yahel

Reputation: 8550

If you are using http as a protocol to initiate your inputstream, you may try the RANGE header.

Take a look here :

http://www.west-wind.com/Weblog/posts/244.aspx

Upvotes: 2

Moystard
Moystard

Reputation: 1837

The problem with the skip method is that you have to read the data even if you skip them so you need to receive them. The best solution is probably to request the server only the part you want.

Upvotes: 2

Related Questions