Android读取服务器图片的三种方法

Android读取服务器图片的三种方法,第1张

概述Android链接服务器获取图片在此提供三种方法,已通过验证,无误。方法一:publicstaticBitmapgetImage(Stringpath){

AndroID链接服务器获取图片在此提供三种方法,已通过验证,无误。

方法一:

public static Bitmap getimage(String path){      try {     httpURLConnection conn = (httpURLConnection) new URL(path).openConnection();     conn.setConnectTimeout(5000);     conn.setRequestMethod("GET");     System.out.println("tDW1");     if(conn.getResponseCode() == 200){       inputStream inputStream = conn.getinputStream();       Bitmap bitmap = BitmapFactory.decodeStream(inputStream);         return bitmap;     }   } catch (Exception e) {     e.printstacktrace();   }   return null; } 

在第一种方法中,从conn的输入流中获取数据将其转化为Bitmap型数据。

在功能代码中:

image.setimageBitmap(getimage("路径")); 

image为ImageVIEw型控件。

第二种方法:

public static Bitmap getimage1(String path){        httpGet get = new httpGet(path);     httpClIEnt clIEnt = new DefaulthttpClIEnt();     Bitmap pic = null;      try {       httpResponse response = clIEnt.execute(get);       httpentity entity = response.getEntity();       inputStream is = entity.getContent();        pic = BitmapFactory.decodeStream(is);  // 关键是这句代   } catch (Exception e) {     e.printstacktrace();   }   return pic; } 

这个方法类似上面那个方法。在功能代码中设置是一样的

第三种方法:

public static Uri getimage2(String path,file cacheDir){     file localfile = new file(cacheDir,MD5.getMD5(path)+path.substring(path.lastIndexOf(".")));     if(localfile.exists()){       return Uri.fromfile(localfile);     }else     {       httpURLConnection conn;       try {         conn = (httpURLConnection) new URL(path).openConnection();         conn.setConnectTimeout(5000);         conn.setRequestMethod("GET");         if(conn.getResponseCode() == 200){           System.out.println("tDW");           fileOutputStream outputStream = new fileOutputStream(localfile);           inputStream inputStream = conn.getinputStream();           byte[] buffer = new byte[1024];           int length = 0;           while((length=inputStream.read(buffer))!=-1){             outputStream.write(buffer,length);           }           inputStream.close();           outputStream.close();           return Uri.fromfile(localfile);         }       } catch (Exception e) {         // Todo auto-generated catch block         e.printstacktrace();       }     }     return null;     } 

第三种方法,将从服务器获取的数据存入本地的文件中,如果文件已存在,则不需要从服务器重新获取数据。
在功能代码中:

image.setimageURI(getimage2(path,cache)); 

上面代码中设置图片为缓存设置,这样如果图片资源更新了,则需要重新命名文件的名字,这样才能够重新加载新图片。

cache = new file(Environment.getExternalStorageDirectory(),"cache"); if(!cache.exists()){   cache.mkdirs(); } 

这里是设置 缓存图片的路径。
以上为三种方法。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android读取服务器图片的三种方法全部内容,希望文章能够帮你解决Android读取服务器图片的三种方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1146147.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存