为什么我一次只能从okhttp.Response InputStream中读取2048个字节? [英] why can I only read 2048 bytes at a time from an okhttp.Response InputStream?

查看:640
本文介绍了为什么我一次只能从okhttp.Response InputStream中读取2048个字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用OkHttp GET请求下载文件:

I am downloading a file using an OkHttp GET request:

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
...
OkHttpClient okClient = new OkHttpClient();
Request request = Request.Builder().url(url).get();
Response response = okClient.newCall(request).execute();

我从响应正文中读取并用BufferedInputStream装饰它,缓冲区大小为4096:

I read from the response body and decorating it with a BufferedInputStream, with a buffer size of 4096:

BufferedInputStream in = new BufferedInputStream(response.body().byteStream(), 4096);

但是,当我尝试从缓冲区读取时,第一次读取返回1179个字节.之后,我一次只能读取2048个字节:

However, when I try to read from the buffer, the first read returns 1179 bytes. After that, I am only able to read 2048 bytes at a time:

byte[] buffer = new byte[4096];
while (true) {
    int bytesRead = in.read(buffer); //bytesRead is always 2048, except the first read
    if (bytesRead == -1) break;
}

几个相关问题:

  1. 是什么导致第一次读取返回1179个字节?某种文件头?
  2. 为什么从InputStream中读取的内容被分页为2048字节,而不是BufferedInputStream包装器指定的值?
  3. 是否可以将OkHttpClient配置为从缓冲区读取2048个以上的字节?
  1. What could be causing the first read to return 1179 bytes? Some sort of file header?
  2. Why are reads from the InputStream being paged to a size of 2048 bytes, instead of the value specified by the BufferedInputStream wrapper?
  3. Is there a way to configure the OkHttpClient to read more than 2048 bytes from the buffer?

推荐答案

什么可能导致第一次读取返回1179个字节?某种文件头?

What could be causing the first read to return 1179 bytes? Some sort of file header?

您正在读取的响应的HTTP标头为869字节.

The HTTP header is 869 bytes for the response you are reading.

为什么从InputStream读取的页面被分页为2048个字节,而不是BufferedInputStream包装器指定的值?

Why are reads from the InputStream being paged to a size of 2048 bytes, instead of the value specified by the BufferedInputStream wrapper?

您必须深入挖掘BufferedInputStream才能找出为什么它没有将两个页面连接在一起.

You'd have to go digging in BufferedInputStream to find out why it's not joining two pages together.

OkHttp的InputStream正在处理2048个块,因为它使用其中的一个池来保存分配.

The InputStream from OkHttp is handing 2048 chunks because it uses a pool of them to save allocations.

是否可以将OkHttpClient配置为从缓冲区读取超过2048个字节?

Is there a way to configure the OkHttpClient to read more than 2048 bytes from the buffer?

否.

根据所执行的操作,通常使用response.body().source()中的BufferedSource比使用BufferedInputStream有更好的时间.您可以在 Okio回购上了解有关它们的更多信息.

Depending on what you are doing, you'll generally have a much better time using the BufferedSource from response.body().source() rather than using BufferedInputStream. You can learn more about them on the Okio repo.

这篇关于为什么我一次只能从okhttp.Response InputStream中读取2048个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆