使用 HTTP 请求下载文件的一部分 [英] Downloading a portion of a File using HTTP Requests

查看:49
本文介绍了使用 HTTP 请求下载文件的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试下载 PDF 文件的一部分(仅用于测试范围"标题).我请求服务器获取 Range 中的字节 (0-24),但仍然没有从内容中获取前 25 个字节(一部分),而是获取了全长内容.此外,我得到的响应代码不是 206(部分内容),而是 200.

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.

这是我的代码:

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

这是输出:
<代码>响应代码:200
内容长度:94973848
下载大小:94973848

提前致谢.

推荐答案

尝试更改以下内容:

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

与:

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

根据规范 14.35.1 字节范围

同样,根据规范14.5 Accept-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));

这篇关于使用 HTTP 请求下载文件的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆