Android请求标头范围:bytes = 207358401-414716804,破坏文件?

时间:2016-06-14 09:29:32

标签: android video byte httpurlconnection

我正在尝试使用HttpURLConnection从服务器下载600MB视频文件。所以我用过" range"标题下载3个部分的文件,并在下载完所有字节后准备三个单独的视频文件。

mycode的:

    try{

     URL url = new URL(downloadUrl);
     connection =(HttpURLConnection) url.openConnection();
     connection.setRequestMethod("POST");
     connection.setRequestProperty("Connection", "keep-alive");
     connection.setRequestProperty("Content-type", "");
     connection.setRequestProperty("User-Agent", "LibHttp/1.3.8");
     connection.setRequestProperty("Range", "bytes=414716804-622075205");
     connection.connect();

     input = connection.getInputStream();

     byte data[] = new byte[4096];

     int count =0;

       while ((count = input.read(data)) != -1) {

            String path = "/sdcard/test.flv";
            saveTofile(data,path,count);

       }   

   } catch (Exception e) {
     System.out.println(SampleThread.TAG+" Download Exception   "+e.toString());
   }  


public void saveTofile(byte[] data,String path,int count){

    OutputStream fos = null;

    try {

        fos = new FileOutputStream(new File(path),true);

        // Writes bytes from the specified byte array to this file output stream

        fos.write(data,0,count);
    }
    catch (FileNotFoundException e) {
        System.out.println("File not found" + e);
    }
    catch (IOException ioe) {
        System.out.println("Exception while writing file " + ioe);
    }
    finally {
        // close the streams using close method
        try {
            if (fos != null) {
                fos.close();
            }
        }
        catch (IOException ioe) {
            System.out.println("Error while closing stream: " + ioe);
        }
    }

}

但是在玩的时候:

Part - 1:Range:bytes = 0-207358401 //播放得很好//

Part - 2:Range:bytes = 207358401-414716804 //文件损坏不播放//

Part - 3:Range:bytes = 414716804-622075205 //文件损坏不播放//

我无法找到问题,为什么第1部分视频文件播放绝对正常,但其余两部分根本没有播放,说这些文件不是视频文件。

请建议我解决我的问题。

1 个答案:

答案 0 :(得分:0)

字节范围是包容性的,而不是偏移长度。使用以下范围应该起作用

第1部分:范围:字节= 0-207358401

Part - 2:Range:bytes = 207358402-414716804

第3部分:范围:字节= 414716805 -