Does InputStream.read (byte [], 0 length) stop earlier?

I wrote something to read the request stream (containing gzipped data) from the incoming HttpServletRequest (the "request" below), however it seems that the usual method of reading InputStream does not actually read all the content?

My code is:

InputStream requestStream = request.getInputStream();
if ((length = request.getContentLength()) != -1)
{
    received = new byte[length];
    requestStream.read(received, 0, length);
}
else
{
    // create a variable length list of bytes
    List<Byte> bytes = new ArrayList<Byte>();

    boolean endLoop = false;
    while (!endLoop)
    {
        // try and read the next value from the stream.. if not -1, add it to the list as a byte. if
        // it is, we've reached the end.
        int currentByte = requestStream.read();
        if (currentByte != -1)
            bytes.add((byte) currentByte);
        else
            endLoop = true;
    }
    // initialize the final byte[] to the right length and add each byte into it in the right order.
    received = new byte[bytes.size()];
    for (int i = 0; i < bytes.size(); i++)
    {
        received[i] = bytes.get(i);
    }
}

What I found during testing was that sometimes the top part (when the length of the content is present) simply stops reading part of the path through the incoming request stream and leaves the rest of the received byte array empty. If I just force it to run the else part of the if statement at all times, it reads perfectly and all expected bytes are placed in the “received” ones.

, , , - , read (byte [], int, int) ? , , . , gzipped- , ?

+5
2

while , . , , len :

, len , , , .

if ((length = request.getContentLength()) != -1)
{
    received = new byte[length];
    int pos = 0;
    do {
        int read = requestStream.read(received, pos, length-pos);

        // check for end of file or error
        if (read == -1) {
            break;
        } else {
            pos += read;
        }
    } while (pos < length);
}

EDIT: .

+8
+1

All Articles