问题描述
我正在使用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;
}
几个相关问题:
- 是什么导致第一次读取返回1179个字节?某种文件头?
- 为什么从
InputStream
中读取的内容被分页为2048字节,而不是BufferedInputStream
包装器指定的值? - 是否可以将
OkHttpClient
配置为从缓冲区读取2048个以上的字节?
- What could be causing the first read to return 1179 bytes? Some sort of file header?
- Why are reads from the
InputStream
being paged to a size of 2048 bytes, instead of the value specified by theBufferedInputStream
wrapper? - Is there a way to configure the
OkHttpClient
to read more than 2048 bytes from the buffer?
推荐答案
您正在读取的响应的HTTP标头为869字节.
The HTTP header is 869 bytes for the response you are reading.
您必须深入挖掘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.
否.
根据所执行的操作,通常使用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个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!