Android-网络图片获取方法

来源:互联网 发布:拉拉热门交友软件 编辑:程序博客网 时间:2024/04/28 22:32

Android-网络图片获取方法

private Bitmap getImageFromInternet(String url){    HttpURLConnection conn = null;  //创建一个Http对象    try{        URL mUrl = new URL(url);    //创建一个URL对象        conn = (HttpURLConnection) mUrl.openConnection();   //得到Http的连接对象        conn.setRequestMethod("GET");   //设置请求方法        conn.setConnecTimeout(10000);   //设置连接超时时间,超过10秒,报异常        conn.setReadTimeout(5000);          //设置读取超时时间,超过5秒,报异常        int responseCode = conn.getResponseCode();  //获取响应码        if(responseCode == 200){        //是否访问成功            InputStream is = conn.getInputStream();     //获取服务器返回的流数据            Bitmap bitmap = BitmapFactory.decodeStream(is);     //根据数据流创建一个Bitmap位图对象            return bitmap;  //返回Bitmap对象        }else{            Log.i(TAG,"访问失败:"+responseCode);    //访问失败,提示        }    }catch(Exception e){        e.printStackTrace();    }finally{        if(conn != null){            conn.disconnect();  //最后,断开连接        }    }    return null;}
0 0
原创粉丝点击