如何从android中的URL下载文件的一部分?

tet*_*tet 4 java android

我试图使用setRequestProperty("Range","bytes ="+ startbytes +" - "+ endbytes)下载给定下载URL的文件的一部分; 以下代码段显示了我要执行的操作.

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);
Run Code Online (Sandbox Code Playgroud)

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

Sar*_*fan 7

选项1

如果您不需要知道内容长度:

[小心,不要打电话给connection.getContentLength().如果你打电话,你会得到例外.如果你需要打电话,那么检查第二个选项]

URL url = new URL(aurl[0]);
HttpURLConnection connection =(HttpURLConnection) url.openConnection();
connection.setRequestProperty("Range", "bytes=" + 0 + "-" + 1000);
//Note that, response code will be 206 (Partial Content) instead of usual 200 (OK)
if(connection.getResponseCode() == HttpURLConnection.HTTP_PARTIAL){
    //Your code here to read response data
}
Run Code Online (Sandbox Code Playgroud)

选项2

如果您需要知道内容长度:

URL url = new URL(aurl[0]);
//First make a HEAD call to get the content length  
HttpURLConnection connection =(HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD");
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
    int lengthOfFile = connection.getContentLength();
    Log.d("ERF","Length of file: "+ lengthOfFile);
    connection.disconnect();

    //Now that we know the content lenght, make the GET call
    connection =(HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Range", "bytes=" + 0 + "-" + 1000);
    //Note that, response code will be 206 (Partial Content) instead of usual 200 (OK)
    if(connection.getResponseCode() == HttpURLConnection.HTTP_PARTIAL){
        //Your code here to read response data

    }
}
Run Code Online (Sandbox Code Playgroud)