代码不复杂,直接把完整代码贴上。
这次是用到很旧的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; } }