Downloading a portion of a File using HTTP Requests

Jeffry Young picture Jeffry Young · Jul 14, 2013 · Viewed 12.2k times · Source

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.

Answer

Syed Muhammad Humayun picture Syed Muhammad Humayun · Jul 15, 2013

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