Android 没有读取完整的 HttpURLConnection InputStream 内容

Android is not reading full HttpURLConnection InputStream content

我有以下代码已在 Java 应用程序 class 中测试过 WORKS 它调用我的后端 Java servlet 并将二进制字节读入 byte[]

private byte[] readResponse(HttpURLConnection connection) throws IOException {
    InputStream inputStream = connection.getInputStream();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    int contentLength = connection.getContentLength();
    byte[] buffer;
    if (contentLength>-1) {
        buffer = new byte[contentLength];
        int readCount = bufferedInputStream.read(buffer, 0 , contentLength);
        System.out.println("Content Length is " + contentLength + " Read Count is " + readCount);
    }
    return buffer;
}

现在我将这个 Java 代码移动到我的 Android 代码中,不知何故它只读取部分内容,服务器发送大约 5709 字节而 Android 应用程序只读取 1448 字节

有趣的是,如果我进入调试模式并将断点放在行

int readCount = bufferedInputStream.read(buffer, 0 , contentLength);

并逐步调试,变量

readCount

可以达到5709字节。 如果我没有设置断点,它就变成了 1448 字节。 为什么?

好像是延时问题?

谢谢。 此致,

这对我有用:

    // Read response
    //int responseCode = connection.getResponseCode();
    StringBuilder response = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
           response.append(line);
    }

    reader.close();
    response.toString();

感谢大家的帮助,特别是网友greenapps的回答。 我将加载过程分成 1kb 缓冲区并解决了问题。 以下是代码:

private byte[] readResponse(HttpURLConnection connection) throws IOException {
    InputStream inputStream = connection.getInputStream();
    int contentLength = connection.getContentLength();
    byte[] buffer;
    buffer = new byte[contentLength];
    int bufferSize = 1024;
    int bytesRemaining = contentLength;
    int loadedBytes;
    for (int i = 0; i < contentLength; i = i + loadedBytes) {
        int readCount =   bytesRemaining > bufferSize ? bufferSize : bytesRemaining;
        loadedBytes = inputStream.read(buffer, i , readCount);
        bytesRemaining = bytesRemaining - loadedBytes;
    }
    return buffer;
}