0

根据https://futurestud.io/tutorials/retrofit-2-how-to-download-files-from-server上的精彩教程,我正在使用 REST API 的 Retrofit2 实现下载文件。

我的 API 接口声明了@GETas @Streaming,实际上,当我从InputStream给定的 by中读取时byteStream(),我可以读取整个 29 MB 文件。

我想做的是以 4 MB 的块读取所有内容,所以我使用的是 Okio 的方便BufferedSource. 问题是我的调用只request(4*1024*1024)返回一次,尽管总文件大小约为 29 MB。true

我的爪哇:

      @Streaming @GET Call<ResponseBody> get(@Url String url);

      // ...

      Response<ResponseBody> response = api.get("https://my.file.url");

      final int bufSize = 4*1024*1024;
      byte[] buffer;
      long total;

      InputStream is = response.body().byteStream();
      BufferedSource ss = Okio.buffer(Okio.source(is));
      // Is this the same as ss=response.body().source() ??

      while (ss.request(bufSize)) {
         buffer = ss.readByteArray();
         total += doSomethingUsefulWith(buffer);
         System.out.println("Running total: " + total);
      }

      // Capture the < 4MB residue
      buffer = ss.readByteArray();

      if (buffer.length > 0) {
         total += doSomethingUsefulWith(buffer);
         System.out.println("Total: " + total);
      }

      System.out.println("That's all, folks!");

控制台输出:

Running total: 4194304
That's all, folks!

同样,原始文件InputStream确实给了我完整的 29 MB,我以前做过。我误解了request()吗?我究竟做错了什么?

4

1 回答 1

1

调用ss.readByteArray()会将整个正文读入一个字节数组。你的意思是做ss.readByteArray(bufSize)吗?

于 2019-04-10T00:01:40.857 回答