Question

i'm missing something in a pretty easy task: i have to check if incoming request inputstream is gzipped and ungzip its content. this without using content-type. i thought about something like this:

check if request is gzipped:

private boolean isGZIPed( HttpServletRequest request )
{
    boolean isGziped = false;
    try
    {
        PushbackInputStream pb = new PushbackInputStream( request.getInputStream(), 2 );
        byte[] signature = new byte[2];
        pb.read( signature );
        pb.unread( signature );
        int head = ( (int)signature[0] & 0xff ) | ( ( signature[1] << 8 ) & 0xff00 );
        isGziped = GZIPInputStream.GZIP_MAGIC == head;
    }
    catch( Exception ioe )
    {
        logger.error(ioe);
    }
    return isGziped;
}

ungzip it if it is gziped indeed:

if(isGziped(request) 
{
    GZIPInputStream gzis = new GZIPInputStream( request.getInputStream() );
    InputStreamReader reader = new InputStreamReader( gzis );
    ...
}

my problem is that new GZIPInputStream( request.getInputStream() ) always throws "not a gzip format" exception. what do i miss?

Was it helpful?

Solution

When you read from the push-back input stream you remove data from the request input stream. "Unreading" bytes only pushes them to the push-back stream, not to the underlaying stream.

You should create the GZIPInputStream with the push back stream so that the bytes you read and pushed back can be re-read:

GZIPInputStream gzis = new GZIPInputStream( pb );

This means the push-back stream has to be declared in the appropriate scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top