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

时间:2011-11-11 07:00:19

标签: android file download zip

我正在开发一个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

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

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。 我的代码是正确的还是我必须使用别的东西来handel zipfiles。

编辑已解决:

我非常抱歉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之前是必需的..

Thnx每1快速响应..

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

您的.zip文件网址或 .zip文件大小(0字节大小)中存在错误,因为如果我们下载此.zip文件(来自网址)由您提供)从Web浏览器然后下载0字节大小。

Downloaded .zip file URL