android 服务器获取图片路径,Android读取服务器图片的三种方法

本文介绍了在Android中从服务器获取并显示图片的三种方法。第一种使用HttpURLConnection,第二种采用HttpGet与HttpClient,第三种则涉及本地缓存,先检查本地文件是否存在,若不存在才从服务器下载。所有方法均经过验证,适用于不同的应用场景。
摘要由CSDN通过智能技术生成

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 block

e.printStackTrace();

}

}

return null;

}

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

在功能代码中:

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

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

cache = new File(Environment.getExternalStorageDirectory(),"cache");

if(!cache.exists()){

cache.mkdirs();

}

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

以上为三种方法。

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

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值