/工具类
public Bitmap getBitmap(String s) { URL url=null; HttpURLConnection urlConnection=null; Bitmap bitmap = null; try { url=new URL(s); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(5000); int res = urlConnection.getResponseCode(); if(res==200){ InputStream is = urlConnection.getInputStream(); bitmap = BitmapFactory.decodeStream(is);//把inputStream数据流转换为Bitmap } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap; }
//MainActivity
new AsyncTask<String,Integer,Bitmap>(){ @Override protected Bitmap doInBackground(String... params) { //网络代码请求图片 Bitmap bitmap = new NetJson().getBitmap("http:"+li.get(i).getImage_url()); return bitmap; } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); if(bitmap != null){ viewHodler.iv1.setImageBitmap(bitmap); } } }.execute();