Android 从 Api 下载 Zip 并存储在 SD 卡中

标签 android file download zip

我正在开发一个 API,该 API 返回一个包含多个 XML 文件的 zip 文件,我必须在提取 zip 文件后单独解析这些文件。

这是链接(将下载 zip 文件):

http://clinicaltrials.gov/ct2/results?term=&recr=&rslt=&type=&cond=&intr=&outc=&lead=&spons=&id=&state1=&cntry1=&state2=&cntry2=&state3=&cntry3=&locn=&gndr=Female&age=0&rcv_s=&rcv_e=&lup_s=&lup_e=studyxml=true

这是我当前将 zip 文件保存在 sdcard 中的代码:

File root = Environment.getExternalStorageDirectory();
String url= "http://clinicaltrials.gov/ct2/results?term=&recr=&rslt=&type=&cond=&intr=&outc=&lead=&spons=&id=&state1=&cntry1=&state2=&cntry2=&state3=&cntry3=&locn=&gndr=Female&age=0&rcv_s=&rcv_e=&lup_s=&lup_e=xml=true";


try {

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoInput(true);
    conn.setConnectTimeout(10000); // timeout 10 secs
    conn.connect();
    InputStream input = conn.getInputStream();

    FileOutputStream fOut = new FileOutputStream(new File(root, "new.zip"));
    int byteCount = 0;
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = input.read(buffer)) != -1) {

        fOut.write(buffer, 0, bytesRead);
        byteCount += bytesRead;

    }
    fOut.flush();
    fOut.close();

} catch (Exception e) {

    e.printStackTrace();

}

问题: New.zip 文件正在 sdcard 中创建,但似乎没有下载任何文件,文件大小也为 0kb。 我的代码是否正确,或者我必须使用其他东西来处理 zip 文件。

编辑已解决:

非常抱歉api链接无效...应该是

http://clinicaltrials.gov/ct2/results?term=&recr=&rslt=&type=&cond=&intr=&outc=&lead=&spons=&id=&state1=&cntry1=&state2=&cntry2=&state3=&cntry3=&locn=&gndr=Female&age=0&rcv_s=&rcv_e=&lup_s=&lup_e=&studyxml=true

& 在 studtxml 之前是必需的..

感谢每 1 个快速响应..

最佳答案

您的 .zip 文件 URL.zip 文件大小(0 字节大小) 有问题,因为如果我们下载此 .zip 文件(来自 URL由您提供)从网络浏览器然后也以 0 字节大小下载。

Downloaded .zip file URL .

关于Android 从 Api 下载 Zip 并存储在 SD 卡中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8090674/

相关文章:

android - 如何将字符串标签添加到 MPAndroidChart

android - Prestashop 语言标志图标在移动设备上看起来很糟糕

android - 如何设置 ActionMode LayoutParams 以使自定义 View match_parent?

file - 将变量写入 Ansible 中的文件

php - 如何使用 PHP 下载 HTML?

c# - 重定向到 "Thank you"页面并立即提供下载文件的保存对话框

安卓工作室 : difference between src/androidTest and src/main folders?

java - 是否可以将 Java 应用程序设置为默认文件打开器?

javascript - 如何在javascript中将字符串转换为文件对象?

download - 为什么我不能让 st_read 从压缩文件中打开 shapefile? (如果保存在本地 Onedrive 文件夹中但未在 R 中解压缩,则会读取 map )