开发者

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

开发者 https://www.devze.com 2023-02-06 11:21 出处:网络
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

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()+"-");  
}


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消