Java:在 URLConnection 中恢复下载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3414438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:44:13  来源:igfitidea点击:

Java: resume Download in URLConnection

javaresumeurlconnection

提问by RYN

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?

我正在我知道支持简历的服务器上测试它。
我下载了一些字节。(72720)
然后尝试恢复它。
然后我用十六进制编辑器打开文件,在偏移量 72720 处重复第一个字节:
字节 0-36:FLV........................onMetaData
Bytes 72720-72756:FLV..................onMetaData 从头
开始下载!
当我通过 wget 执行它时,它会正确执行并通过 Content-Range 字段进行响应!
wget 日志中的服务器响应为“302 FOUND”和“206 Partial Content”。
“302 FOUND”会导致问题吗?

What is the problem ?
Thanks.

问题是什么 ?
谢谢。

回答by NG.

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

根据规范小写范围说明符。此外,如果您的部分文件是 500 字节,这意味着您拥有的字节范围是 0-499,而您想要 500+。

回答by Maurice Perry

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

问题在于(fcheck.length() - 1):这应该是fcheck.length()