0

经过大量搜索后,我无法找到解决文件下载问题的解决方案。

以下脚本旨在通过 WebViewClient从远程(Hotmail)服务器下载 csv 文件。

登录过程是通过他们的标准网站完成的,但我想使用以下下载类捕获下载的 csv 文件并存储在自定义位置。

它适用于直接链接到例如site.com/file.pdf的文件的 URL,但不适用于处理过的 URL,例如site.com/downloadFile.php?n=xxxx,它只是挂起,直到连接重置由远程服务器

    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]);
    }

     @Override
     protected void onPostExecute (String result){

     super.onPostExecute(result);

     mProgressDialog.dismiss();
     mProgressDialog = null;
     }


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

        try {

            Log.i("File download", "Started from :"+sUrl[0]);

            URL url = new URL(sUrl[0]);
            //URLConnection connection = url.openConnection();
            File myDir = new File(Environment.getExternalStorageDirectory() + "/myDir");

            // create the directory if it doesnt exist
            if (!myDir.exists()) myDir.mkdirs();            

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();


            //Follow redirects so as some sites redirect to the file location
            connection.setInstanceFollowRedirects(true);        
            connection.setDoOutput(true);           

            connection.connect();

            File outputFile     =   new File(myDir, "hotmail_contacts.csv");

            // 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(outputFile);

            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);
            }


            connection.disconnect();
            output.flush();
            output.close();
            input.close();

            Log.i("File download", "complete");

        } catch (Exception e) {

            Log.e("File download", "error: " + e.getMessage());

        }
        return null;
    }
}

上面的 AsyncTask 在onDownloadStart(....)方法中调用如下:

public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long length) {

        Log.i("File download", "URL:" + url 
                + " UserAgent:" + userAgent
                + "ContentDisposition:" + contentDisposition 
                + "Mime:"+ mimeType + "Length:" + Long.toString(length));



        // instantiate it within the onCreate method
        mProgressDialog = new ProgressDialog(Email_import.this);
        mProgressDialog.setMessage("File download");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        // start a new download
        DownloadFile downloadFile = new DownloadFile();
        downloadFile.execute(url);

    }// end onCreate

所有相关权限都在清单中,例如写入外部存储、互联网和读取网络状态。

我在这里错过了什么吗?任何帮助将非常感激

4

1 回答 1

0

在查看了 [此处][1] 列出的另一篇文章后

[1]:将文件从 webview 下载到自定义文件夹我已经对我的代码进行了一些调整,以使用HttpClient对象将 URL 作为HttpPost请求调用,如下所示,它似乎运行良好:

                // Create client and set our specific user-agent string
            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost(sUrl[0]);               
            request.setHeader("User-Agent", sUrl[1]);               

            HttpResponse response = client.execute(request);

            Log.i("File download", "Started from :" + sUrl[0]);

            File myDir = new File(Environment.getExternalStorageDirectory() + "/myDir");

            // create the directory if it doesnt exist
            if (!myDir.exists())    myDir.mkdirs();

            File outputFile = new File(myDir, "hotmail_contacts.csv");

            InputStream input   = response.getEntity().getContent();
于 2012-04-18T21:56:26.967 回答