通过互联网实现下载文件的简历 [英] Implementing resume for download files via internet

查看:125
本文介绍了通过互联网实现下载文件的简历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码下载文件正常工作时没有实现 resume ,在阅读了更多解决方案来实现并解决问题之后我知道我必须检查 Last-Modified 标题并将其设置为连接,

my below code for downloading file work fine when don't implementing resume for that, after read more solution to implementing that and resolve problem i know i must check Last-Modified header and set it for connection,

但我不能这样做因为我得到错误,例如 android无法在建立连接后设置请求属性或者我获得 null httpURLConnection

but i can't do that because of i get error such as android Cannot set request property after connection is made or i get null for httpURLConnection,

我正在使用此参考

getHeaderField heaser return:

getHeaderField heaser return:

{
  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]
}

现在如何设置恢复下载文件?

now how can i set that to have resume for download files?

GitHub Link

public void run() {
    final URL         url;
    HttpURLConnection httpURLConnection = null;
    try {
        try {
            url = new URL(mUrl);
            String lastModified = httpURLConnection.getHeaderField("Last-Modified");
            if (!lastModified.isEmpty()) {
                httpURLConnection.setRequestProperty("If-Range", lastModified);
            }
            httpURLConnection = (HttpURLConnection) url.openConnection();

            if (mFile.exists()) {
                downloadedLength = mFile.length();
                Log.e("downloadedLength ", downloadedLength + "");
                httpURLConnection.setRequestProperty("Range", "bytes=" + downloadedLength + "-");
                fileOutputStream = new FileOutputStream(mFile, true);
            } else {
                fileOutputStream = new FileOutputStream(mFile);
            }
            httpURLConnection.setConnectTimeout(30000);
            httpURLConnection.setReadTimeout(30000);
            httpURLConnection.setRequestMethod("GET");
        } catch (IOException e) {
        }
        final int responseCode;
        final int total;
        try {
            responseCode = httpURLConnection.getResponseCode();
            total = httpURLConnection.getContentLength();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("ER UPDATE ", e.getMessage());
        }
        if (responseCode == 200) {
            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());
    }
}

我还得到 206 响应代码而不是 200

and also i get 206 response code instead of 200

推荐答案

1-你为httpURLConnection获取null,因为你在初始化之前尝试调用它,

1- You are getting null for httpURLConnection because you try to invoke it before being initialized,

即此行

httpURLConnection = (HttpURLConnection) url.openConnection();

应该在此行之前:

String lastModified = httpURLConnection.getHeaderField("Last-Modified");

2-您可以在调用 connect() on httpURLConnection
所以你需要设置你想要的任何东西,然后连接()。这样你不应该得到错误(android连接后无法设置请求属性)

2- you can set the header before calling connect() on httpURLConnection so you need to set whatever you want, then connect(). this way you should not get the error (android Cannot set request property after connection is made)

3- 206 完全正确,这就是你<使用 >范围,这意味着部分内容成功,这就是您正在做的事情,您将获得部分内容,如果您获得完整内容,您将获得 200

3- The 206 is perfectly right, it's what you should expect when using Range and it means Partial Content Success and that's what you are doing, you are getting part of the content, if you are getting full content you would get 200.

所以总结一下,你的代码看起来像这样:
注意:关注// ***查看所需的更改。

so to sum this up, your code can look like this: Note: follow the //*** to see changes required.

编辑:一切都来到此行

httpURLConnection.setRequestProperty("If-Range", lastModified);

设置该属性时会抛出错误,

the error get thrown when you set that Property,

无论如何,当你看这个时,它没有意义,你问最后修改是否等于你从连接中得到的值!,
如果你想这样做你需要存储系统中的 lastModified
然后将它与您从URLConn获得的那个进行比较,并将其与您的文件长度(已下载)进行比较
然后继续完整下载或恢复下载。

Anyways, when you look at this, it's meaningless, you are asking if last-modified is equal to the value that you just got from the connection!, if you want to do this you need to store lastModified in your system, then compare it with the one you got from the URLConn, and compare it to your file length (already downloaded) then proceed with full download or resume download.

在下面找到新代码:

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

这篇关于通过互联网实现下载文件的简历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆