0

I have a gzipped JSON resource in my application that I want to serve up via a servlet. Browsers disagree on exactly why, but none of them will actually load my content. Does something look wrong with this code?

public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(200);

        InputStream in = <get an input stream to my gzipped data>;

        resp.setIntHeader("Content-Length", in.available());
        OutputStream out = resp.getOutputStream();

        out.write(IOUtils.toByteArray(in));
        out.close();

        resp.setHeader("Content-Encoding", "gzip");
        resp.setHeader("Content-Type", "application/json");
    }
}
Ben Dilts
  • 10,535
  • 16
  • 54
  • 85

1 Answers1

0

I think the answer you are looking for is available in the link in the accepted answer in this thread - Serve Gzipped content with Java Servlets.

This includes a working example from the O'Reilly site.

However I would question your need for introducing this cross curling concern and gzip the contents manually. Assuming you are using Apache or a fork thereof, I would suggest you look at mod_deflate it is configurable and powerful and releases you from the need to write boilerplate code for gzipping responses.

Community
  • 1
  • 1
Y123
  • 915
  • 13
  • 30