2017-07-16 32 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