7

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

4 回答 4

11

尝试更改以下内容:

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

和:

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

根据规范14.35.1 字节范围

同样,根据规范14.5 Accept-Ranges,您还可以使用以下命令检查您的服务器是否实际支持部分内容检索:

boolean support = urlConnection.getHeaderField("Accept-Ranges").equals("bytes");
System.out.println("Partial content retrieval support = " + (support ? "Yes" : "No));
于 2013-07-14T22:42:58.463 回答
1

如果服务器支持它(并且 HTTP 1.1 服务器应该),那么只有这样你才能使用范围请求......如果你想做的只是检查,那么只需发送 HEAD 请求而不是 GET 请求。相同的标题,相同的一切,只是“HEAD”而不是“GET”。如果您收到 206 响应,您将知道 Range 受支持,否则您将收到 200 响应。

于 2013-07-14T21:45:07.480 回答
-2

您必须在setRequestProperty之前连接到 url

改变:

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

至:

urlConnection.connect();
urlConnection.setRequestProperty("Range", "Bytes=0-24");
于 2017-03-22T17:19:17.093 回答
-3

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

于 2013-07-14T21:30:52.060 回答