Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/208.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么我一次只能从okhttp.Response输入流读取2048字节?_Java_Android_Networking_Okhttp_Okio - Fatal编程技术网

Java 为什么我一次只能从okhttp.Response输入流读取2048字节?

Java 为什么我一次只能从okhttp.Response输入流读取2048字节?,java,android,networking,okhttp,okio,Java,Android,Networking,Okhttp,Okio,我正在使用OkHttp GET请求下载文件: 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 resp

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

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();
我从响应体中读取数据,并用缓冲区大小为4096的
BufferedInputStream
对其进行修饰:

BufferedInputStream in = new BufferedInputStream(response.body().byteStream(), 4096);
但是,当我尝试从缓冲区读取时,第一次读取返回1179字节。之后,我一次只能读取2048字节:

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个字节
  • 是什么导致第一次读取返回1179字节?某种文件头

    HTTP头是您正在读取的响应的869字节

    为什么从InputStream读取的数据被分页为2048字节的大小,而不是BufferedInputStream包装器指定的值

    您必须深入研究
    BufferedInputStream
    以找出它为什么不将两个页面连接在一起

    来自OkHttp的
    InputStream
    正在处理2048个块,因为它使用它们的池来保存分配

    有没有办法将OkHttpClient配置为从缓冲区读取2048字节以上的数据

    没有



    根据您正在做的事情,通常使用
    response.body().source()
    中的
    BufferedSource
    比使用
    BufferedInputStream
    会更好。您可以在上了解更多关于它们的信息。

    谢谢您的解释,杰克。我不知道source()方法,我将查看Okio。在这种情况下,我们如何下载文件?从我的服务下载10MB需要很长时间别管我的问题,使用这个()解决了速度问题。