Download part of a file using HTTP requests

I am trying to download part of a PDF file (only for testing the Range header). I requested a server for bytes (0-24) in Range, but instead of getting the first 25 bytes (part) from the content, I get full-sized content. Moreover, instead of getting the response code as 206 (partial content), I get a 200 response code.

Here is 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 conclusion:
Respnse Code: 200
Content-Length: 94973848
Downloaded Size: 94973848

Thanks at Advance.

+6
source share
4 answers

Try changing the following:

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

with:

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

according to specification 14.35.1 Byte Ranges

Similarly, according to the Accept-Ranges specification 14.5 , you can also check if your server really supports partial content searches or not using the following:

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

If the server supports it (and HTTP 1.1 servers), 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. The same headings, the same, just β€œHEAD”, not β€œGET”. If you get a 206 response, you will find out that Range is supported, and otherwise you will get a 200 response.

+1
source

I think the correct heading is "Content-Range", not "Range" as you use.

-1
source

You need to connect to the URL before setRequestProperty

Edit:

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

To:

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

Source: https://habr.com/ru/post/949423/


All Articles