How to download files from net programmatically in Android?

I'd like to point out that Android 2.3 (API Level 9) introduces a new system service called the DownloadManager. If you're OK with only supporting 2.3, then you should definitely use it. If not, you can either:

  1. Check if the DownloadManager is available and use it if it is. If it's not (Android < 2.3), download the file yourself, for example as described by xil3.
  2. Don't use DownloadManager at all, if you think it's too much work. However, I strongly believe you will benefit from its use.

Here's some code that I recently wrote just for that:

    try {
      URL u = new URL("http://your.url/file.zip");
      InputStream is = u.openStream();

      DataInputStream dis = new DataInputStream(is);

      byte[] buffer = new byte[1024];
      int length;

      FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/" + "file.zip"));
      while ((length = dis.read(buffer))>0) {
        fos.write(buffer, 0, length);
      }

    } catch (MalformedURLException mue) {
      Log.e("SYNC getUpdate", "malformed url error", mue);
    } catch (IOException ioe) {
      Log.e("SYNC getUpdate", "io error", ioe);
    } catch (SecurityException se) {
      Log.e("SYNC getUpdate", "security error", se);
    }

This downloads the file and puts it on your sdcard.

You could probably modify this to suit your needs. :)