How to download a part of a file from URL in android?

前端 未结 2 1651
北海茫月
北海茫月 2020-12-18 09:02

I am trying to download a part of file given the download URL using setRequestProperty(\"Range\",\"bytes=\" + startbytes + \"-\" + endbytes); The following code snippet show

2条回答
  •  再見小時候
    2020-12-18 09:39

    Option 1

    If you do not need to know the content length:

    [Beware, do not call the connection.getContentLength(). If you call that, you will get the exception. If you need to call it, then check the second option]

    URL url = new URL(aurl[0]);
    HttpURLConnection connection =(HttpURLConnection) url.openConnection();
    connection.setRequestProperty("Range", "bytes=" + 0 + "-" + 1000);
    //Note that, response code will be 206 (Partial Content) instead of usual 200 (OK)
    if(connection.getResponseCode() == HttpURLConnection.HTTP_PARTIAL){
        //Your code here to read response data
    }
    

    Option 2

    If you need to know the content length:

    URL url = new URL(aurl[0]);
    //First make a HEAD call to get the content length  
    HttpURLConnection connection =(HttpURLConnection) url.openConnection();
    connection.setRequestMethod("HEAD");
    if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
        int lengthOfFile = connection.getContentLength();
        Log.d("ERF","Length of file: "+ lengthOfFile);
        connection.disconnect();
    
        //Now that we know the content lenght, make the GET call
        connection =(HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Range", "bytes=" + 0 + "-" + 1000);
        //Note that, response code will be 206 (Partial Content) instead of usual 200 (OK)
        if(connection.getResponseCode() == HttpURLConnection.HTTP_PARTIAL){
            //Your code here to read response data
    
        }
    }
    

提交回复
热议问题