【问题标题】:Android: Download Returned Zip file from URLAndroid:从 URL 下载返回的 Zip 文件
【发布时间】:2012-07-31 10:55:32
【问题描述】:

如果我有一个 URL,当在网络浏览器中提交时,会弹出一个对话框来保存一个 zip 文件...我将如何在 android 中捕获和下载这个 zip 文件?

【问题讨论】:

    标签: android url zip webserver download


    【解决方案1】:
    public void downloadFromUrl(String url, String outputFileName) {
    
    
        File dir = new File(Environment.getExternalStorageDirectory() + "/");
        if (dir.exists() == false) {
            dir.mkdirs();
        }
        try {
            URL downloadUrl = new URL(url); // you can write any link here
    
            File file = new File(dir, outputFileName);          
            /* Open a connection to that URL. */
            URLConnection ucon = downloadUrl.openConnection();
    
            /*
             * Define InputStreams to read from the URLConnection.
             */
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
    
            /*
             * Read bytes to the Buffer until there is nothing more to read(-1).
             */
            ByteArrayBuffer baf = new ByteArrayBuffer(5000);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
    
            /* Convert the Bytes read to a String. */
            FileOutputStream fos = new FileOutputStream(file);          
            fos.write(baf.toByteArray());
            fos.flush();
            fos.close();
    
    
    
    
        } catch (IOException e) {
            e.printStackTrace();
    
    
        }
    
    
    
    }
    

    【讨论】:

    • 这就像一个魅力......有时它可能会抛出“networkOnMainThreadException”。在这种情况下,在 AsnycTask 中执行此过程就可以了。
    • 像魅力一样工作。非常感谢:)
    【解决方案2】:

    使用DownloadManager 下载Url,虽然我不确定是否有任何重定向,但DownloadManager 会处理它。

    【讨论】:

    • 哇,我不明白你的连接和管理以及你的输入流的真棒示例...我阅读了文档....但我不知道如何输入“公共静态最终字符串” COLUMN_REASON" 嗯……(讽刺)
    猜你喜欢
    • 2012-03-14
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多