我在我的应用程序中使用了一项服务,该服务曾经用于在后台下载一些“ apk”文件。
我想用接收到的文件大小检查下载的文件大小,以确保完全获得“ apk”。
但是当我使用response.body().contentLength()时为-1!

这是我的代码:

 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;
    }
  }

最佳答案

-1表示Web服务器不提供有关文件长度的任何信息。

改造获得标头content-length。如果不存在,则response.body().contentLength()返回-1

08-18 12:18