0

尝试使用以下代码从服务器下载大约 38 个视频文件,由于某种原因,它在下载过程中不断停止在不同的点,我主要得到一个

java.net.SocketException: Connection timed out

我想知道如何以更少的错误执行此操作

我的代码如下

private class DownloadFile extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            mProgressDialog.setProgress(progress[0]);
            mProgressDialog.setMessage("Downloading "+(i+1)+" of "+downloadURL.length);
        }

        @Override
        protected String doInBackground(String... sUrl) {
            try {

                for(int i = 0; i < sUrl.length; i++){

                    URL url = new URL("http://myvideo.info/videos/"+sUrl[i]);
                    URLConnection connection = null;
                    try {

                        connection = url.openConnection();
                        connection.setConnectTimeout(15000);
                        connection.setReadTimeout(15000);
                    } catch (java.net.SocketTimeoutException e) {
                        e.printStackTrace();
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                    connection.connect();
                    // this will be useful so that you can show a typical 0-100% progress bar
                    int fileLength = connection.getContentLength();

                    // download the file
                    InputStream input = new BufferedInputStream(url.openStream());
                    OutputStream output = new FileOutputStream("/sdcard/"+file_rename[i]);

                    byte data[] = new byte[1024];
                    long total = 0;
                    int count;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // publishing the progress....
                        publishProgress((int) (total * 100 / fileLength));
                        output.write(data, 0, count);
                    }

                    output.flush();
                    output.close();
                    input.close();
                }

            } catch (Exception e) {
                Log.e("PP", "PP", e);
            }
            return null;
        }

        protected void onPostExecute(String jsonResult) {
            mProgressDialog.dismiss();
        }
    }
4

2 回答 2

0

您确定服务器在不到 15 秒内响应吗?(这是我看到您设置的超时)。如果文件很大,您应该单独下载它们,看看下载器管理器,您可以使用它轻松下载大文件。

于 2013-07-08T10:07:33.953 回答
0

你用的是什么下载管理器?我建议将您的超时更改为最大值。就个人而言,您的代码似乎很好。我认为这将是您的下载管理器和超时。希望这可以帮助。

于 2013-07-08T10:20:11.553 回答