1
2 import javax.servlet.http.HttpServlet;
3 import javax.servlet.http.HttpServletRequest;
4 import javax.servlet.http.HttpServletResponse;
5 import java.io.BufferedInputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.PrintWriter;
9 import java.util.zip.GZIPInputStream;
10
11 /**
12 * @author Julius Davies
13 * @author http://juliusdavies.ca/
14 * @since 22-Mar-2006
15 */
16 public class GZIPServlet extends HttpServlet
17 {
18 public void doPost( HttpServletRequest req, HttpServletResponse res )
19 throws IOException
20 {
21 // This servlet just unzips a POST with gzip Content-Encoding,
22 // prints off the first 4KB (unzipped) in the response, and
23 // reports the total unzipped size.
24
25 res.setContentType( "text/plain" );
26 res.setCharacterEncoding( "UTF-8" );
27 PrintWriter writer = res.getWriter();
28
29 String contentEncoding = req.getHeader( "Content-Encoding" );
30 boolean isGzip = false;
31 if ( contentEncoding != null )
32 {
33 isGzip = "gzip".equalsIgnoreCase( contentEncoding.trim() );
34 }
35 if ( isGzip )
36 {
37 InputStream in = req.getInputStream();
38 in = new BufferedInputStream( in );
39 in = new GZIPInputStream( in );
40
41 StringBuffer buf = new StringBuffer( 4096 );
42 int c = in.read();
43 int count = 0;
44 while ( c >= 0 )
45 {
46 count++;
47 byte b = (byte) c;
48 if ( count <= 4096 )
49 {
50 buf.append( (char) b );
51 }
52 c = in.read();
53 }
54
55 writer.println( "First 4KB: " );
56 writer.println( "-------------------------------------------" );
57 writer.println( buf.toString() );
58 writer.println( "-------------------------------------------" );
59 writer.println( "Content unzipped to " + count + " bytes." );
60 }
61 else
62 {
63 writer.println( "Content-Encoding is not gzip!" );
64 writer.println( "-------------------------------------------" );
65 writer.println( "Content-Encoding: [" + contentEncoding + "]" );
66 }
67
68 writer.close();
69 }
70
71
72 }
73