jsonjbosscompressionjboss7.xcontent-encoding

Content-length in response body and content-length header don't match


When I am debugging my code on my ide, I see the response is good, but as soon as it reaches client, it is truncated. One more thing truncation only happens nodeData field is empty

I am applying gzip compression using servlet filters. When I use any other type of content encoding such as "br", "delate", everything is working as expected.

This issue came into existence after I updgraded my JBOSS to version 7.4 EAP

These are my response headers:-

Content-Encoding: gzip
Content-Length: 78
Content-Type: text/html;charset=UTF-8
Date: Tue, 30 Apr 2024 08:43:47 GMT

Response:

{ "status" : "OK" ,"lastModifiedStamp":"1713954485629","no

Expected response from server:

{ "status" : "OK" ,"lastModifiedStamp":"1713954485629","nodeData":[]}

Solution

  • The issue was that my the above json response (only for that response), the content length of the gzipped content is bigger than the actual content.

    The content length is set from the original response, but data written to response output stream is of the zipped response, due to which response was getting truncated. In my source code I was setting the content length of the zipped data but I was doing it after it is written to the response's output stream. All that was required to was set content length before writing the data to output stream.

    Old

            ByteArrayOutputStream compressed = new ByteArrayOutputStream();
            GZIPOutputStream gzout = new GZIPOutputStream(compressed);
            byte[] data = wrapper.getData();
            gzout.write(data);
            gzout.flush();
            gzout.close();
            httpResponse.setHeader("Content-Encoding", "gzip");
            out.write(compressed.toByteArray());
            response.setContentLength(compressed.size());
    

    New

            ByteArrayOutputStream compressed = new 
            ByteArrayOutputStream();
            GZIPOutputStream gzout = new GZIPOutputStream(compressed);
            byte[] data = wrapper.getData();
            gzout.write(data);
            gzout.flush();
            gzout.close();
            httpResponse.setHeader("Content-Encoding", "gzip");
            response.setContentLength(compressed.size());
            out.write(compressed.toByteArray());
    

    Don't know how is it still working in jboss 7.2 and wildfly 26, 15