如何从android中的URL下载文件的一部分? [英] How to download a part of a file from URL in android?

查看:174
本文介绍了如何从android中的URL下载文件的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用setRequestProperty(Range,bytes =+ startbytes + - + endbytes)下载给定下载URL的文件的一部分;以下代码片段显示了我要做的事情。

I am trying to download a part of file given the download URL using setRequestProperty("Range","bytes=" + startbytes + "-" + endbytes); The following code snippet shows what I am trying to do.

protected String doInBackground(String... aurl) {
    int count;
    Log.d(TAG,"Entered");
    try {

        URL url = new URL(aurl[0]);
        HttpURLConnection connection =(HttpURLConnection) url.openConnection();

        int lengthOfFile = connection.getContentLength();

        Log.d(TAG,"Length of file: "+ lengthOfFile);

        connection.setRequestProperty("Range", "bytes=" + 0 + "-" + 1000);

问题在于,引发了一个异常,即连接后无法设置请求属性制作。请帮我解决这个问题。

The problem is that, an exception is being raised, which says "Cannot set request property after connection is made". Please help me resolve this issue.

推荐答案

假设您正在使用HTTP进行下载,那么您将需要使用HEAD http动词和RANGE http标题。

Assuming you're using HTTP for the download, you'll want to use the HEAD http verb and RANGE http header.

HEAD将为您提供文件大小(如果可用),然后RANGE允许您下载字节范围。

HEAD will give you the filesize (if available), and then RANGE lets you download a byte range.

获得文件大小后,将其分成大致相等大小的块,并为每个块生成下载线程。完成所有操作后,按正确的顺序编写文件块。

Once you have the filesize, divide it into roughly equal sized chunks and spawn download thread for each chunk. Once all are done, write the file chunks in the correct order.

如果您不知道如何使用RANGE标头,这里有另一个SO答案,解释如何: https://stackoverflow.com/a/6323043/1355166

If you don't know how to use the RANGE header, here's another SO answer that explains how: https://stackoverflow.com/a/6323043/1355166

要将文件分成块,请使用此选项,然后开始下载过程,

To make file into chunks use this, and start the downloading process,

private void getBytesFromFile(File file) throws IOException {
    FileInputStream is = new FileInputStream(file); //videorecorder stores video to file

    java.nio.channels.FileChannel fc = is.getChannel();
    java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(10000);

    int chunkCount = 0;

    byte[] bytes;

    while(fc.read(bb) >= 0){
        bb.flip();
        //save the part of the file into a chunk
        bytes = bb.array();
        storeByteArrayToFile(bytes, mRecordingFile + "." + chunkCount);//mRecordingFile is the (String)path to file
        chunkCount++;
        bb.clear();
    }
}

private void storeByteArrayToFile(byte[] bytesToSave, String path) throws IOException {
    FileOutputStream fOut = new FileOutputStream(path);
    try {
        fOut.write(bytesToSave);
    }
    catch (Exception ex) {
        Log.e("ERROR", ex.getMessage());
    }
    finally {
        fOut.close();
    }
}

这篇关于如何从android中的URL下载文件的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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