首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >文件下载挂起

文件下载挂起
EN

Stack Overflow用户
提问于 2012-04-18 13:52:26
回答 1查看 1.5K关注 0票数 0

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

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

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

它适用于直接链接到例如,site.com/file.pdf的文件的URL,但不会在处理过的URL(如site.com/downloadFile.php?n=xxxx )上工作,在那里它只是挂起,直到远程服务器重新设置连接。

代码语言:javascript
复制
    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;
    }
}

在onDownloadStart(....)方法中调用上述AsyncTask,如下所示:

代码语言:javascript
复制
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

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

我是不是漏掉了什么?任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-18 21:56:26

在看了另一篇文章之后

1:Download a file from webview to a custom folder,我已经对我的代码做了一些调整,使用一个HttpClient对象将URL作为HttpPost请求调用,如下所示,它看起来工作得很好:

代码语言:javascript
复制
                // 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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10210851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档