Android读取服务器图片的三种方法
Android链接服务器获取图片在此提供三种方法,已通过验证,无误。
方法一:
publicstaticBitmapgetImage(Stringpath){
try{
HttpURLConnectionconn=(HttpURLConnection)newURL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
System.out.println("tdw1");
if(conn.getResponseCode()==200){
InputStreaminputStream=conn.getInputStream();
Bitmapbitmap=BitmapFactory.decodeStream(inputStream);
returnbitmap;
}
}catch(Exceptione){
e.printStackTrace();
}
returnnull;
}
在第一种方法中,从conn的输入流中获取数据将其转化为Bitmap型数据。
在功能代码中:
image.setImageBitmap(getImage("路径"));
image为ImageView型控件。
第二种方法:
publicstaticBitmapgetImage1(Stringpath){
HttpGetget=newHttpGet(path);
HttpClientclient=newDefaultHttpClient();
Bitmappic=null;
try{
HttpResponseresponse=client.execute(get);
HttpEntityentity=response.getEntity();
InputStreamis=entity.getContent();
pic=BitmapFactory.decodeStream(is);//关键是这句代
}catch(Exceptione){
e.printStackTrace();
}
returnpic;
}
这个方法类似上面那个方法。在功能代码中设置是一样的
第三种方法:
publicstaticUrigetImage2(Stringpath,FilecacheDir){
FilelocalFile=newFile(cacheDir,MD5.getMD5(path)+path.substring(path.lastIndexOf(".")));
if(localFile.exists()){
returnUri.fromFile(localFile);
}else
{
HttpURLConnectionconn;
try{
conn=(HttpURLConnection)newURL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode()==200){
System.out.println("tdw");
FileOutputStreamoutputStream=newFileOutputStream(localFile);
InputStreaminputStream=conn.getInputStream();
byte[]buffer=newbyte[1024];
intlength=0;
while((length=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,length);
}
inputStream.close();
outputStream.close();
returnUri.fromFile(localFile);
}
}catch(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
returnnull;
}
第三种方法,将从服务器获取的数据存入本地的文件中,如果文件已存在,则不需要从服务器重新获取数据。
在功能代码中:
image.setImageURI(getImage2(path,cache));
上面代码中设置图片为缓存设置,这样如果图片资源更新了,则需要重新命名文件的名字,这样才能够重新加载新图片。
cache=newFile(Environment.getExternalStorageDirectory(),"cache");
if(!cache.exists()){
cache.mkdirs();
}
这里是设置缓存图片的路径。
以上为三种方法。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。