本篇文章为大家展示了Android应用中是如何读取服务器中的图片的,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

为肥西等地区用户提供了全套网页设计制作服务,及肥西网站建设行业解决方案。主营业务为成都网站建设、成都做网站、肥西网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!
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();
}
上述内容就是Android应用中是如何读取服务器中的图片的,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。