代碼不復雜,直接把完整代碼貼上。
這次是用到很舊的HttpURLConnection,那為什麽會用這個,因為我本來想轉回okhttp的,可實在沒時間轉,項目就已經做下去了,結果轉不回來。
package com.paradise.electronic.eparadise2.util; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by Administrator on 17-11-12. */ public class BitMap { // 餓漢式 private static BitMap instance = new BitMap(); private BitMap(){} public static BitMap getInstance(){ return instance; } /* * get image from network * @param [String]imageURL * @return [BitMap]image */ public Bitmap returnBitMap(String url){ URL myFileUrl = null; Bitmap bitmap = null; try { myFileUrl = new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); is.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } }
