Downloading a portion of a File using HTTP Requests

你。 提交于 2019-11-26 21:38:04

问题


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.


回答1:


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



回答2:


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.




回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/17643851/downloading-a-portion-of-a-file-using-http-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!