Java: resume Download in URLConnection

前提是你 提交于 2019-11-26 08:22:27

问题


I wrote a program that downloads some files from some servers.
Currently program works properly.
But I want to add resume support to it.
I\'m doing it like this But the result file is corrupted:

....

File fcheck=new File(SaveDir+\"/\"+filename);
if(resumebox.isSelected() && fcheck.exists()){
    connection.setRequestProperty(\"Range\", \"Bytes=\"+(fcheck.length())+\"-\");
}

connection.setDoInput(true);
connection.setDoOutput(true);

BufferedInputStream in = new BufferedInputStream (connection.getInputStream()); 

pbar.setIndeterminate(false);
pbar.setStringPainted(true);

java.io.FileOutputStream fos ;
if(resumebox.isSelected()){
    if(fcheck.exists()){
        if(connection.getHeaderField(\"Accept-Ranges\").equals(\"bytes\")){
            fos = new java.io.FileOutputStream(SaveDir+\"/\"+filename,true);
        }else{
            fos = new java.io.FileOutputStream(SaveDir+\"/\"+filename);
        }
    }else{
        fos = new java.io.FileOutputStream(SaveDir+\"/\"+filename);
    }
}else{
    fos = new java.io.FileOutputStream(SaveDir+\"/\"+filename);
}

....

I\'m Testing it on a server that I know supports resume.
I downloaded some bytes.(72720)
Then Tried to resume it.
Then I opened file with a Hex editor , At offset 72720 the first Bytes are repeated:
Bytes 0-36: FLV.............«..........onMetaData
Bytes 72720-72756: FLV.............«..........onMetaData
It Starts download from the begining!
While when I do it by wget it does correctly and responses by Content-Range field!
Server responses with \"302 FOUND\" and a \"206 Partial Content\" in wget log.
Can \"302 FOUND\" cause the problem?

What is the problem ?
Thanks.


回答1:


Try:

connection.setRequestProperty("Range", "bytes=" + fcheck.length() + "-");

Lowercase the range specifier per the spec. Also, if your partial file was 500 bytes, that means your byte range that you have is 0-499, and you want 500+.




回答2:


The problem is in (fcheck.length() - 1): this should be fcheck.length().



来源:https://stackoverflow.com/questions/3414438/java-resume-download-in-urlconnection

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