Android和服务器通信,从服务器端获取图片

来源:互联网 发布:mysql 添加复合主键 编辑:程序博客网 时间:2024/05/16 01:03

在android开发过程中,与服务器的通信是无处不在的,今天将要讲一个小问题,就是如何从服务器端获取图片:

我们通过查阅资料得知,服务器端以json的形式发给android客户端图片的url地址,例如:https://img1.doubanio.com//mpic//s28023953.jpg  (这是一幅豆瓣书籍图片)

android端获取到该json数据,解析出来这个url地址之后,我们通过编程实现客户端本地读取图片。

new Thread(new Runnable(){@Overridepublic void run() {DownloadBitmap(url1,iv_show);}}).start();


public void DownloadBitmap(String bmurl,final ImageView iv)    //bmurl是解析出来的utl, iv是显示图片的imageView控件{Bitmap bm=null;InputStream is =null;BufferedInputStream bis=null;try{URL  url=new URL(bmurl);URLConnection connection=url.openConnection();bis=new BufferedInputStream(connection.getInputStream());bm= BitmapFactory.decodeStream(bis);final Bitmap bm1 = bm;runOnUiThread(new Runnable() {@Overridepublic void run() {iv.setImageBitmap(bm1);}});}catch (Exception e){e.printStackTrace();}finally {try {if(bis!=null)bis.close();if (is!=null)is.close();}catch (Exception e){e.printStackTrace();}}}

需要强调的几点:

1、利用URLConnection做的时候,直接url.openConnection()即可

2、包装成为一个缓冲流让BitmapFactory  decode一下下

3、注意:注意:android主线程无法进行耗时操作,所以必须是子线程访问网络,主线程更改UI,所以这里采用了runOnUiThread()方法,就是在主线程中更新UI。

0 0
原创粉丝点击