Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Compressed servlet output with GZIP  RSS feed

Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,
I've seen a million places on the web that post a solution to compressing servlet output. Basically the solution encapsulates the HttpServletResponse OutputStream in a GZIPOutputStream. Some solutions encapsulate the GZIPOutputStream in a PrintWriter - very handy so that you can do write() with a string, eliminating the step of converting the string to a byte array.
I've been able to get a little standalone program to generate an output file via PrintWriter encapsulating GZIPOutputStream and then I can read the file back in again using GZIPInputStream.
But when I do this in my servlet code, the input stream just shows up empty back at the client - I get "unexpected end of ZLIB input stream".
I am not running this in a browser, by the way, the client is a standalone application.
Any suggestions for why the InputStream turns up empty? And are there any straightforward ways to monitor what is getting written to that output stream on the server side?
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try to first run this program.. I have tested it on IE as well as on netscape.
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.sql.*;
public class EncodedPage extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out;
String encodings = request.getHeader("Accept-Encoding");
String encodeFlag = request.getParameter("encoding");
String title;
if ((encodings != null) &&
(encodings.indexOf("gzip") != -1) &&
!"none".equals(encodeFlag)) {
title = "Page Encoded with GZip";
OutputStream out1 = response.getOutputStream();
out = new PrintWriter(new GZIPOutputStream(out1), false);
response.setHeader("Content-Encoding", "gzip");
} else {
title = "Unencoded Page";
out = response.getWriter();
out.println( "<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n");
String line = "Blah, blah, blah, blah, blah. " +
"Yadda, yadda, yadda, yadda.";
Always look on the bright side of life. At least this ad is really tiny:
ScroogeXHTML 7.2 - RTF to HTML5 / XHTML converter
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!