我想从Android的Zippyshare网站下载文件。

问题是返回的内容长度为-1。因此,我无法下载有效的文件。

这是我的代码

public class DownloadFileDemo1 extends Activity {

ProgressBar pb;
Dialog dialog;
int downloadedSize = 0;
int totalSize = 0;
TextView cur_val;
String dwnload_file_path = "http://www17.zippyshare.com/i/95748527/55444/image.jpeg";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
             showProgress(dwnload_file_path);

                new Thread(new Runnable() {
                    public void run() {
                         downloadFile();
                    }
                  }).start();
}

void downloadFile(){

    try {
        URL url = new URL(dwnload_file_path);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("Accept-Encoding", "gzip");
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);

        //connect
        urlConnection.connect();

        //set the path where we want to save the file
        File SDCardRoot = Environment.getExternalStorageDirectory();
        //create a new file, to save the downloaded file
        File file = new File(SDCardRoot,"downloaded_file.png");

        FileOutputStream fileOutput = new FileOutputStream(file);

        //Stream used for reading the data from the internet
        InputStream inputStream = urlConnection.getInputStream();

        System.out.println("ENCODING"+urlConnection.getContentEncoding());

        if ("gzip".equals(urlConnection.getContentEncoding())) {
            inputStream = new GZIPInputStream(inputStream);
            }
            InputSource is = new InputSource(inputStream);

        //this is the total size of the file which we are downloading
        totalSize = urlConnection.getContentLength();

        runOnUiThread(new Runnable() {
            public void run() {
                pb.setMax(totalSize);
            }
        });

        //create a buffer...
        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            // update the progressbar //
            runOnUiThread(new Runnable() {
                public void run() {
                    pb.setProgress(downloadedSize);
                    float per = ((float)downloadedSize/totalSize) * 100;
                    cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
                }
            });
        }
        //close the output stream when complete //
        fileOutput.close();
        runOnUiThread(new Runnable() {
            public void run() {
                // pb.dismiss(); // if you want close it..
            }
        });

    } catch (final MalformedURLException e) {
        showError("Error : MalformedURLException " + e);
        e.printStackTrace();
    } catch (final IOException e) {
        showError("Error : IOException " + e);
        e.printStackTrace();
    }
    catch (final Exception e) {
        showError("Error : Please check your internet connection " + e);
    }
}

void showError(final String err){
    runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(DownloadFileDemo1.this, err, Toast.LENGTH_LONG).show();
        }
    });
}

void showProgress(String file_path){
    dialog = new Dialog(DownloadFileDemo1.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.myprogressdialog);
    dialog.setTitle("Download Progress");

    TextView text = (TextView) dialog.findViewById(R.id.tv1);
    text.setText("Downloading file from ... " + file_path);
    cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
    cur_val.setText("Starting download...");
    dialog.show();

    pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
    pb.setProgress(0);
    pb.setProgressDrawable(getResources().getDrawable(R.drawable.green_progress));
}
}


我怎么解决这个问题?

最佳答案

根据getContentLength的文档:


  返回响应头指定的内容长度(以字节为单位)
  字段content-length;如果未设置或不能设置为-1,则为-1
  表示为int。


如果您将检查链接here,则会发现未设置“内容长度”。

(我要补充一点,我没有完全检查您的代码,但是通常在带有缓冲区的主下载循环中-正在下载某些内容,但是我没有检查它是否正确)

编辑:我要'讨厌'家伙,那给了我'-1'。我正在帮助详细链接以及如何进行检查,为什么内容长度返回-1,并且有人给我否定的信息。我更改了一点downloadFile函数,仅用于下载文件,而不更新UI,然后我们得到了:

void downloadFile(){

    try {
        URL url = new URL(dwnload_file_path);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("Accept-Encoding", "gzip");
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);

        //connect
        urlConnection.connect();

        //set the path where we want to save the file
        //create a new file, to save the downloaded file
        File file = new File("downloaded_file.png");

        FileOutputStream fileOutput = new FileOutputStream(file);

        //Stream used for reading the data from the internet
        InputStream inputStream = urlConnection.getInputStream();

        System.out.println("ENCODING"+urlConnection.getContentEncoding());

        if ("gzip".equals(urlConnection.getContentEncoding())) {
            inputStream = new GZIPInputStream(inputStream);
        }
        InputSource is = new InputSource(inputStream);

        //this is the total size of the file which we are downloading
        totalSize = urlConnection.getContentLength();


        //create a buffer...
        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            // update the progressbar //
        }
        //close the output stream when complete //
        fileOutput.close();


    } catch (final MalformedURLException e) {
        e.printStackTrace();
    } catch (final IOException e) {
        e.printStackTrace();
    }
    catch (final Exception e) {
        e.printStackTrace();
    }
}


当我检查此代码正在下载文件时,但这不是此图像,而是zippyshare的html页面,因为zippy具有某种保护作用,可以从其站点下载文件。

10-04 11:00
查看更多