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, 0, length);}inputStream.close();outputStream.close();return Uri.fromFile(localFile);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}return null;}

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

在功能代码中:

image.setImageURI(getImage2(path, cache));

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

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

这里是设置 缓存图片的路径。

以上为三种方法。


更多相关文章

  1. Android实现静态广播监听器的方法
  2. TabHost的基本使用方法
  3. android上传图片以及POST字符串
  4. android去掉头部label的方法
  5. Android实现圆形图片的两种方式
  6. 图片上动态添加文字
  7. android —— 常用代码utils

随机推荐

  1. 分页查询 效率最高
  2. SQL Server 不存在或访问被拒绝(转)
  3. Java 实现连接sql server 2000
  4. sql 多条件组合查询,并根据指定类别找出所
  5. sql 随机抽取几条数据的方法 推荐
  6. 对有insert触发器表取IDENTITY值时发现的
  7. SQL SERVER 查询正在实行的SQL语句
  8. SQL语句查询是否为空 =null及null
  9. SQLserver 实现分组统计查询(按月、小时分
  10. SQL Server日志过大会影响查询结果