Created
April 5, 2013 14:17
-
-
Save alexfu/5319597 to your computer and use it in GitHub Desktop.
Downloading an image from the network using HttpURLConnection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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