2017-07-16 27 views
0

我在我的應用程序中使用了一項服務,我用它來翻新以在後臺下載一些「apk」文件。 我想檢查下載的文件大小與收到的文件大小,以確保我完全得到「apk」。 但是當我使用response.body().contentLength()它是-1!如何獲取ContentLength在改造

這是我的代碼:

private void downloadAppFromServer(String url, final String fileId) { 

    APIService downloadService = ServiceGenerator.createServiceFile(APIService.class, "181412655", "181412655"); 

    Call<ResponseBody> call = downloadService.downloadFileWithDynamicUrlSync(url); 
    call.enqueue(new Callback<ResponseBody>() { 
     @Override 
     public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) { 
     if (response.isSuccess()) { 
    new AsyncTask<Void, Void, Void>() { 
      @Override 
      protected Void doInBackground(Void... voids) { 

       Log.d("LOGO", "server contacted and has file"); 
       Log.d("LOGO", "FILE SIZE: " + response.body().contentLength()); 


       boolean writtenToDisk = writeResponseBodyToDisk(response.body(), fileId); 
       Log.d("LOGO", "file download was a success? " + writtenToDisk); 

       return null; 
      } 
      }.execute(); 

     } 
     } 

     @Override 
     public void onFailure(Call<ResponseBody> call, Throwable t) { 


    }); 
    } 

這是我writeToDisk方法:

private boolean writeResponseBodyToDisk(ResponseBody body, String fileId) { 

    try { 

     // Location to save downloaded file and filename 
     File DownloadFile = new File(G.DIR_APK + "/" + fileId + ".apk"); 
     InputStream inputStream = null; 
     OutputStream outputStream = null; 
     try { 

     byte[] fileReader = new byte[4096]; 
     long fileSize = body.contentLength(); 
     long fileSizeDownloaded = 0; 
     inputStream = body.byteStream(); 
      Log.d("LOGO", "file size is: " + fileSize); //This is -1 ! 
     outputStream = new FileOutputStream(DownloadFile); 
     while (true) { 
      int read = inputStream.read(fileReader); 
      if (read == -1) { 
      break; 
      } 
      outputStream.write(fileReader, 0, read); 
      fileSizeDownloaded += read; 
     } 
     outputStream.flush(); 
     if (fileSize == fileSizeDownloaded) { 
      return true; 
     } else { 
      return false; 
     } 
     } catch (IOException e) { 

     return false; 
     } finally { 
     if (inputStream != null) { 
      inputStream.close(); 
     } 
     if (outputStream != null) { 
      outputStream.close(); 
     } 
     } 

    } catch (IOException e) { 
     return false; 
    } 
    } 

回答

2

-1表示,這並不爲您提供有關文件的長度的任何信息的Web服務器。

改造獲取標題content-length。如果它不存在response.body().contentLength()返回-1