import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.zip.GZIPInputStream; /** * @author Julius Davies * @author http://juliusdavies.ca/ * @since 22-Mar-2006 */ public class GZIPServlet extends HttpServlet { public void doPost( HttpServletRequest req, HttpServletResponse res ) throws IOException { // This servlet just unzips a POST with gzip Content-Encoding, // prints off the first 4KB (unzipped) in the response, and // reports the total unzipped size. res.setContentType( "text/plain" ); res.setCharacterEncoding( "UTF-8" ); PrintWriter writer = res.getWriter(); String contentEncoding = req.getHeader( "Content-Encoding" ); boolean isGzip = false; if ( contentEncoding != null ) { isGzip = "gzip".equalsIgnoreCase( contentEncoding.trim() ); } if ( isGzip ) { InputStream in = req.getInputStream(); in = new BufferedInputStream( in ); in = new GZIPInputStream( in ); StringBuffer buf = new StringBuffer( 4096 ); int c = in.read(); int count = 0; while ( c >= 0 ) { count++; byte b = (byte) c; if ( count <= 4096 ) { buf.append( (char) b ); } c = in.read(); } writer.println( "First 4KB: " ); writer.println( "-------------------------------------------" ); writer.println( buf.toString() ); writer.println( "-------------------------------------------" ); writer.println( "Content unzipped to " + count + " bytes." ); } else { writer.println( "Content-Encoding is not gzip!" ); writer.println( "-------------------------------------------" ); writer.println( "Content-Encoding: [" + contentEncoding + "]" ); } writer.close(); } }