Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

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

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

protected String doInBackground(String... aurl) {
    int count;
    Log.d(TAG,"Entered");
    try {

        URL url = new URL(aurl[0]);
        HttpURLConnection connection =(HttpURLConnection) url.openConnection();

        int lengthOfFile = connection.getContentLength();

        Log.d(TAG,"Length of file: "+ lengthOfFile);

        connection.setRequestProperty("Range", "bytes=" + 0 + "-" + 1000);

The problem is that, an exception is being raised, which says "Cannot set request property after connection is made". Please help me resolve this issue.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...