Downloading a portion of a File using HTTP Requests

14.8k Views Asked by At

I am trying to download a portion of a PDF file (just for testing "Range" header). I requested the server for the bytes (0-24) in Range but still, instead of getting first 25 bytes (a portion) out of the content, I am getting the full length content. Moreover, instead of getting response code as 206 (partial content), I'm getting response code as 200.

Here's my code:

public static void main(String a[]) {
    try {
        URL url = new URL("http://download.oracle.com/otn-pub/java/jdk/7u21-b11/jdk-7u21-windows-x64.exe?AuthParam=1372502269_599691fc0025a1f2da7723b644f44ece");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("Range", "Bytes=0-24");
        urlConnection.connect();

        System.out.println("Respnse Code: " + urlConnection.getResponseCode());
        System.out.println("Content-Length: " + urlConnection.getContentLengthLong());

        InputStream inputStream = urlConnection.getInputStream();
        long size = 0;

        while(inputStream.read() != -1 )
            size++;

        System.out.println("Downloaded Size: " + size);

    }catch(MalformedURLException mue) {
        mue.printStackTrace();
    }catch(IOException ioe) {
        ioe.printStackTrace();
    }
}

Here's the output:
Respnse Code: 200
Content-Length: 94973848
Downloaded Size: 94973848

Thanks in Advance.

4

There are 4 best solutions below

2
AudioBubble On

I think the correct header is "Content-Range", not "Range" as you are using.

1
AudioBubble On

If the server supports it (and HTTP 1.1 servers should), only then you can use range requests... and if all you want to do is check, then just send a HEAD request instead of a GET request. Same headers, same everything, just "HEAD" instead of "GET". If you receive a 206 response, you'll know Range is supported, and otherwise you'll get a 200 response.

1
Syed Muhammad Humayun On

Try changing following:

urlConnection.setRequestProperty("Range", "Bytes=0-24");

with:

urlConnection.setRequestProperty("Range", "bytes=0-24");

as per the spec 14.35.1 Byte Ranges

Similarly, as per the spec 14.5 Accept-Ranges, you can also check whether your server actually supports partial content retrieval or not using following:

boolean support = urlConnection.getHeaderField("Accept-Ranges").equals("bytes");
System.out.println("Partial content retrieval support = " + (support ? "Yes" : "No));
0
M.Barati On

You have to connect to url before setRequestProperty

Change:

urlConnection.setRequestProperty("Range", "Bytes=0-24");
urlConnection.connect();

To:

urlConnection.connect();
urlConnection.setRequestProperty("Range", "Bytes=0-24");