Retrofit2.1.0深入学习@GET【第三章】文件下载

2016-09-08  本文已影响164人  Small_Cake

1.建立接口和下载工具类

public class ApkDownloadUtil {    
    interface DownloadInterface{        
    String HOST = "http://p.gdown.baidu.com/";        
    //@Streaming:大文件下载防止数据写入到内存中OOM,小图片可以不用       
    @Streaming       
    @GET        
    Call<ResponseBody> downloadFile(@Url String url); 
   }    
    public static void download(String url, Callback<ResponseBody> callback){        
    DownloadInterface downloadInterface = new Retrofit.Builder().baseUrl(DownloadInterface.HOST).build().create(DownloadInterface.class);  
    downloadInterface.downloadFile(url).enqueue(callback);   
     }
}

2.使用工具类下载,以下载爱奇艺为例

public void download() {    
    String url = "f72c2decfb0ea49d5ef0bb1d20e03f09a4f8ef8df26d18e16bf4c80faf5999972b9ae8fc29b39598f15ab0aa7b65017cc9e26e5a1bcb3ae93188d67b1580e3d4938a81bb93b312d83383c6602f7b777d52651f73c5d0e6346d4a838af1d47fa9971c1fba88f03a5ce139fc1f89dae8cc9fe33323aba5f1ff7640f9f38318115af70106f93f099053ae605477502f2e275000f0b9f5e192f67efad1db0f8505d4";    
    ApkDownloadUtil.download(url, new Callback<ResponseBody>() {        
    @Override        
    public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {            
       if (response.isSuccessful()) {                
        //注意这里要另开线程下载,耗时操作不允许在主线程进行                
        new Thread(new Runnable() {                    
        @Override                    
        public void run() {                                   
            boolean writtenToDiskSucess = writeToDisk(response.body());                        
            L.d("文件下载是否成功= " + writtenToDiskSucess);                    
         }                
        }).start();            
      } else { 
               L.d( "服务器连接失败");           
      }       
    }        
     @Override        
     public void onFailure(Call<ResponseBody> call, Throwable t) {            
      L.e( "error="+t.getMessage());        
      }    
   });
}

3.把下载的文件写入到手机中,并显示下载进度

public Handler mHandler = new Handler(){        
@Override   
 public void handleMessage(Message msg) {        
tvMsg.setText("进度:"+msg.arg1+"%");    
}};

private boolean writeToDisk(ResponseBody body) {    
try {        

File fileDir = new File(Environment.getExternalStorageDirectory()+File.separator+"Download");       
 if (!fileDir.exists()){            
fileDir.mkdir();        
}        

File filePath = new File(fileDir.getPath()+File.separator+"爱奇艺.apk");    
    
InputStream inputStream = null;        
OutputStream outputStream = null;      
  
try {            
    byte[] fileReader = new byte[4096];            
    long fileSize = body.contentLength();           
    long fileSizeDownloaded = 0;            
    inputStream = body.byteStream();            
    outputStream = new FileOutputStream(filePath);            
    while (true) {                
    int read = inputStream.read(fileReader);               
     if (read == -1)break;                
    outputStream.write(fileReader, 0, read);                
    fileSizeDownloaded += read;                
    //发送下载的进度                
    int progress = (int) ((float)fileSizeDownloaded/(float)fileSize*100);                
    Message msg = Message.obtain();                
    msg.arg1 = progress;                
    mHandler.sendMessage(msg);            
  }            
    outputStream.flush();            
    return true;        
  } catch (IOException e) {            
        return false;       
   } finally {            
  if (inputStream != null) {
            inputStream.close();            
    }            
  if (outputStream != null) { 
           outputStream.close();           
   }        
  }   
   } catch (IOException e) {          
     return false;    
  }
}
上一篇下一篇

猜你喜欢

热点阅读