标签:
使用异步任务加载网络图片:
class MyTask extends AsyncTask<String, Void, Bitmap>{ @Override protected Bitmap doInBackground(String... params) { HttpClient client = new DefaultHttpClient(); HttpGet post = new HttpGet(params[0]);//注意请求方式,可能爆出请求方式不被允许 try { HttpResponse response = client.execute(post); int stateCode = response.getStatusLine().getStatusCode(); if(stateCode == 200){ byte[] result = EntityUtils.toByteArray(response.getEntity()); Bitmap bm = BitmapFactory.decodeByteArray(result, 0, result.length); return bm; } } catch (Exception e) { e.printStackTrace(); }return null; } @Override protected void onPostExecute(Bitmap result) { super.onPostExecute(result); if(result != null){ iv.setImageBitmap(result); } } }
加载URL对象来获取网络数据
@Override protected Bitmap doInBackground(String... params) { try { //创建URL对象 URL url = new URL(params[0]); //获取连接 URLConnection conn = url.openConnection(); //设置连接超时, 一般为5s conn.setConnectTimeout(5000); //获取输入流 InputStream in = conn.getInputStream(); Bitmap bm = BitmapFactory.decodeStream(in); return bm; } catch (Exception e) { e.printStackTrace(); }
标签:
原文地址:http://www.cnblogs.com/chengbao/p/5625588.html