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

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

问题描述

我正在尝试下载PDF文件的一部分(仅用于测试Range标题)。我请求服务器获取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();
    }
}

这是输出:


Respnse代码:200

内容长度:94973848

下载大小:94973848

先谢谢。

推荐答案

尝试更改以下内容:

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

with:

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天全站免登陆