您的位置:首页 > 理论基础 > 计算机网络

android网络连接之增加缓存

2016-07-10 19:12 489 查看
final String path = "http://localhost:8999/72.jpg";
   final File file = new File(getCacheDir(), "dd.jpg");
   if(file.exists()){//判断缓存文件是否存在
        Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
        iv.setImageBitmap(bm);
   }else{//下载图片
      Thread t = new Thread(){
          @Override
          public void run() {       
            try {
            URL url = new URL(path);            
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            
            conn.setRequestMethod("GET");          
            conn.setConnectTimeout(5000);            
            conn.setReadTimeout(5000);            
            conn.connect();
            if(conn.getResponseCode() == 200){                
                 InputStream is = conn.getInputStream();
                 FileOutputStream fos = new FileOutputStream(file);
                 byte[] b = new byte[1024];
                 int len = 0;
                 while((len = is.read(b)) != -1){
                 fos.write(b, 0, len);
                 }
                 fos.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: