码迷,mamicode.com
首页 > 移动开发 > 详细

android 加载网络数据(1)

时间:2016-06-29 07:48:28      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

使用异步任务加载网络图片:

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();
            }  

android 加载网络数据(1)

标签:

原文地址:http://www.cnblogs.com/chengbao/p/5625588.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!