Skip to content

Instantly share code, notes, and snippets.

@nighthawk24
Created April 7, 2014 20:15
Show Gist options
  • Save nighthawk24/10043864 to your computer and use it in GitHub Desktop.
Save nighthawk24/10043864 to your computer and use it in GitHub Desktop.
DownloadFile using AsyncTask
new DownloadFile().execute("");
private class DownloadFile extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL("http://ftp.ee.debian.org/debian/ls-lR.gz");
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file.zip");
final byte buffer[] = new byte[16 * 1024];
final InputStream inputStream = connection.getInputStream();
int len1 = 0;
while ((len1 = inputStream.read(buffer)) > 0) {
Log.i("DPR", "doInBackground - downloading file");
output.write(buffer, 0, len1);
}
} catch (Exception e) {
Log.i("DPR", "doInBackground - exception" + e.getMessage());
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
connection.disconnect();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
protected void onPostExecute(String result) {
}
protected void onPreExecute() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment