I Prefer these one:
Creates Bitmap from InputStream and returns it:
public static Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
}
catch (IOException e1) {
e1.printStackTrace();
System.out.println("downloadImage"+ e1.toString());
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
public static InputStream getHttpConnection(String urlString) throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println("downloadImage" + ex.toString());
}
return stream;
}
REMEMBER :
Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client. For Gingerbread and later, HttpURLConnection is the best choice.
From Android 3.x Honeycomb or later, you cannot perform Network IO on the UI thread and doing this throws android.os.NetworkOnMainThreadException. You must use Asynctask instead as shown below
/** AsyncTAsk for Image Bitmap */
private class AsyncGettingBitmapFromUrl extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
System.out.println("doInBackground");
Bitmap bitmap = null;
bitmap = AppMethods.downloadImage(params[0]);
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
System.out.println("bitmap" + bitmap);
}
}