Java 通过internet实现文件下载的简历

Java 通过internet实现文件下载的简历,java,android,download,android-download-manager,Java,Android,Download,Android Download Manager,我下面下载文件的代码在不执行resume时工作正常,在阅读了更多实现该文件的解决方案并解决了问题后,我知道我必须检查上次修改的标题并将其设置为连接 但是我不能这样做,因为我得到了一些错误,比如在建立连接后,android无法设置请求属性,或者对于httpURLConnection,我得到了null 我在用这个 getHeaderFieldheaser返回: { null=[HTTP/1.1 200 OK], Cache-Control=[public], Connection=[

我下面下载文件的代码在不执行
resume
时工作正常,在阅读了更多实现该文件的解决方案并解决了问题后,我知道我必须检查上次修改的
标题并将其设置为连接

但是我不能这样做,因为我得到了一些错误,比如在建立连接后,
android无法设置请求属性
,或者对于
httpURLConnection
,我得到了
null

我在用这个

getHeaderField
heaser返回:

{
  null=[HTTP/1.1 200 OK], 
  Cache-Control=[public], 
  Connection=[keep-alive], 
  Content-Length=[8037404], 
  Content-Md5=[VEqXHCc/Off7a6D0gRFpiQ==], 
  Content-Type=[image/jpeg], 
  Date=[Tue, 19 Jan 2016 07:24:36 GMT], 
  Etag=["544a971c273f39f7fb6ba0f481116989"], 
  Expires=[Sat, 29 Jul 2017 10:07:00 GMT], 
  Last-Modified=[Thu, 18 Dec 2014 08:44:34 GMT], 
  Server=[bws], 
  X-Android-Received-Millis=[1501063623576], 
  X-Android-Response-Source=[NETWORK 200], 
  X-Android-Selected-Protocol=[http/1.1], 
  X-Android-Sent-Millis=[1501063623532]
}
现在,我如何才能设置为下载文件的恢复

另外,我得到的是
206
响应代码,而不是
200

看看答案。 但是无论如何,如果您通过
HTTP
协议下载文件,您可以使用-a系统服务(从API级别9开始)在后台进行长时间运行的下载。它处理
HTTP
连接、连接更改、重新启动,并确保每次下载成功完成。而且它已经支持恢复和进度通知


您可以在by-tag上找到许多类似的教程或示例,以及许多解决方案。

1-您在初始化之前尝试调用httpURLConnection,因此httpURLConnection的值为null

i、 e,这条线

httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("If-Range", lastModified);
应排在这一行之前:

String lastModified = httpURLConnection.getHeaderField("Last-Modified");
2-在调用
httpURLConnection
所以你需要设置你想要的,然后连接()。这样您就不会出现错误(android无法在建立连接后设置请求属性)

3.206是指,当您使用
Range
时,它意味着部分内容成功,这就是您所做的,您将获得部分内容,如果您获得完整内容,您将获得200

总之,您的代码可以如下所示: 注意:按照//***查看所需的更改

编辑:这一切都发生在这一行

httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("If-Range", lastModified);
设置该属性时会引发错误

不管怎样,当你看这个的时候,它是没有意义的,你在问最后修改的值是否等于你刚从连接中得到的值!, 如果要执行此操作,需要在系统中存储lastModified, 然后将其与您从URLConn获得的文件进行比较,并将其与您的文件长度(已下载)进行比较 然后继续完整下载或继续下载

在下面查找新代码:

public void run() {
    myLastModified = getLastModified(mFile.getName()); // get last stored value for this file (use file name or other key)
    int total =0;

    final URL         url;
    HttpURLConnection httpURLConnection = null;
    try {
        try {
            url = new URL(mUrl);

            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoInput(true);

            httpURLConnection.setConnectTimeout(30000);
            httpURLConnection.setReadTimeout(30000);
            httpURLConnection.setRequestMethod("GET");

            //*** new way to handle download process
            total = httpURLConnection.getContentLength();
            if(mFile.exists()){
                if(mFile.length() == total){
                    //we are done, return.
                    return;
                }else{
                    //file was not completly donwloaded, now check lastModified:
                    long lastModified = httpURLConnection.getLastModified();//this gets the header "Last-Modified" and convert to long
                    if (lastModified == myLastModified) { //myLastModified should be retrived on each download and stored locally on ur system
                        downloadedLength = mFile.length();
                        Log.e("downloadedLength ", downloadedLength + "");
                        httpURLConnection = (HttpURLConnection) url.openConnection();
                        httpURLConnection.setDoInput(true);

                        httpURLConnection.setConnectTimeout(30000);
                        httpURLConnection.setReadTimeout(30000);
                        httpURLConnection.setRequestMethod("GET");

                        httpURLConnection.setRequestProperty("Range", "bytes=" + downloadedLength + "-"+ total); //add + total (TO)

                        //append mode
                        fileOutputStream = new FileOutputStream(mFile, true);
                    }else{
                        //file was modified after 1st uncompleted-download:
                        storeLastModified(lastModified, mFile.getName()); // use file name as key. can store in db or file ...

                        //don't set ant Range ... we want full download, with a fresh file
                        fileOutputStream = new FileOutputStream(mFile);
                    }//last mod IF

                }//Length check
            }else{
                //file not exist at all, create new file, set no Range we want full download...
                mFile.createNewFile();
                fileOutputStream = new FileOutputStream(mFile);
            }//file exists.

        } catch (IOException e) {
            e.printStackTrace();
        }
        final int responseCode;

        try {
            responseCode = httpURLConnection.getResponseCode();

        } catch (IOException e) {
            e.printStackTrace();
            Log.e("ER UPDATE ", e.getMessage());
        }

        //*****
        if (responseCode == 200 || responseCode == 206) {
            try {
                inputStream = httpURLConnection.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("IOException ", e.getMessage());
            }
            final byte[] buffer   = new byte[4 * 1024];
            int          length   = -1;
            int          finished = 0;
            long         start    = System.currentTimeMillis();
            try {
                while ((length = inputStream.read(buffer)) != -1) {
                    if (!isDownloading()) {
                        throw new CanceledException("canceled");
                    }
                    fileOutputStream.write(buffer, 0, length);
                    finished += length;
                    if (System.currentTimeMillis() - start > 1000) {
                        onDownloadProgressing(finished, total);
                        start = System.currentTimeMillis();
                    }
                }
                onDownloadCompleted();
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("ER UPDATE ", e.getMessage());
            }
        } else {
            Log.e("responseCode ", responseCode + "");
        }
    } catch (DownloadException e) {
        e.printStackTrace();
        Log.e("ER UPDATE ", e.getMessage());
    } catch (CanceledException e) {
        e.printStackTrace();
        Log.e("ER UPDATE ", e.getMessage());
    }
}

为什么不使用,它“在后台下载,处理HTTP交互,并在出现故障或连接更改和系统重新启动后重试下载”并且已经实现了“resume”?@AndriiOmelchenko对于这个实现,我找不到任何好的documentDownloadManager是完全用于下载文件的,它的工作很好。举个例子吧,也许你是对的,但这不是我问题的答案,这取决于你:)是的,这不是一个答案:只是关于你的问题的其他方法的通知。也许它对某人有用。@Mahdi.Pishguy,是的,你是对的,我没有查看你的代码(逻辑方面的),现在我查看了,我发现“if range”没有太多意义,所以检查我的新代码,查看EDITi获取此错误
java.lang.IllegalStateException:已连接
此行
httpURLConnection.setDoInput(true);
。我评论了
httpURLConnection.connect();
,git上的存储库updated@Mahdi.Pishguy删除它,我为你放了一条评论,如果它引起问题,就删除它。让我们。嗨,伙计,你能帮我吗?谢谢