Skip to content

Instantly share code, notes, and snippets.

@alexfu
Created April 5, 2013 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexfu/5319597 to your computer and use it in GitHub Desktop.
Save alexfu/5319597 to your computer and use it in GitHub Desktop.
Downloading an image from the network using HttpURLConnection
private void fetchImageFromNetwork() {
InputStream input = null;
OutputStream output = null;
HttpURLConnection urlConnection = null;
byte[] buffer = new byte[100*1024];
try {
URL url = new URL(imageUrl);
urlConnection = (HttpURLConnection) url.openConnection();
input = urlConnection.getInputStream();
output = new FileOutputStream(path);
int bytesRead;
while((bytesRead = input.read(buffer, 0, buffer.length)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(input);
if(urlConnection != null)
urlConnection.disconnect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment