介绍
本篇文章为大家展示了Android应用中是如何读取服务器中的图片的,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
Android链接服务器获取图片在此提供三种方法
<强>方法一:强>
公共静态位图getImage (String路径){ 尝试{ HttpURLConnection康涅狄格州=(HttpURLConnection)新的URL(路径).openConnection (); conn.setConnectTimeout (5000); conn.setRequestMethod (“GET"); System.out.println (“tdw1"); 如果(conn.getResponseCode ()==200) { InputStream InputStream=conn.getInputStream (); 位图的位图=BitmapFactory.decodeStream (inputStream); 返回位图; } }捕捉(异常e) { e.printStackTrace (); } 返回null; }
在第一种方法中,从康涅狄格州的输入流中获取数据将其转化为位图型数据。
在功能代码中:
image.setImageBitmap (getImage(“路径“));
图像为ImageView型控件。
<强>第二种方法:
强>
公共静态位图getImage1 (String路径){ HttpGet得到=new HttpGet(路径); HttpClient客户=new DefaultHttpClient (); 位图图片=零; 尝试{ HttpResponse响应=client.execute(得到); HttpEntity实体=response.getEntity (); InputStream是=entity.getContent (); 照片=BitmapFactory.decodeStream(是);//关键是这句代 }捕捉(异常e) { e.printStackTrace (); } 返回图片; }
这个方法类似上面那个方法。在功能代码中设置是一样的
<强>第三种方法:强>
公共静态Uri getImage2 (String路径,文件cacheDir) { 文件localFile=新文件(cacheDir MD5.getMD5(路径)+ path.substring (path.lastIndexOf (“!”))); 如果(localFile.exists ()) { 返回Uri.fromFile (localFile); 其他} { HttpURLConnection康涅狄格州; 尝试{ 康涅狄格州=(HttpURLConnection)新的URL(路径).openConnection (); conn.setConnectTimeout (5000); conn.setRequestMethod (“GET"); 如果(conn.getResponseCode ()==200) { System.out.println (“tdw"); FileOutputStream outputStream=new FileOutputStream (localFile); InputStream InputStream=conn.getInputStream (); byte[]新字节缓冲区=[1024]; int长度=0; 在((长度=read(缓冲))!=1){ outputStream。写(缓冲区,0,长度); } inputStream.close (); outputStream.close (); 返回Uri.fromFile (localFile); } }捕捉(异常e) {//TODO自动生成的catch块 e.printStackTrace (); } } 返回null; }
第三种方法,将从服务器获取的数据存入本地的文件中,如果文件已存在,则不需要从服务器重新获取数据。
在功能代码中:
形象。setImageURI (getImage2(道路、缓存));
上面代码中设置图片为缓存设置,这样如果图片资源更新了,则需要重新命名文件的名字,这样才能够重新加载新图片。
=新文件(Environment.getExternalStorageDirectory (),“cache"); 如果(! cache.exists ()) { cache.mkdirs (); }
上述内容就Android应是用中是如何读取服务器中的图片的,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。