Serve Gzipped content with Java Servlets

后端 未结 7 2145
予麋鹿
予麋鹿 2021-01-05 01:40

I was wondering if there was an easy way to serve GZipped content with Java Servlets. I already have the app up and running so the modifications needed should be to

7条回答
  •  醉梦人生
    2021-01-05 02:03

    This's what I used while learning about servlets. Maybe not usefully, but working!!! Laid below code into public class GZIPEncodingServlet extends HttpServlet {...}

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        if (req.getHeader("Accept-Encoding").contains("gzip")) {
    
            // 'try' block need for closing of stream, of course we can use 'close()' method for our 'PrintWriter' too
            try (PrintWriter printWriter = new PrintWriter(new GZIPOutputStream(resp.getOutputStream()))) {
    
                resp.setHeader("Content-Encoding", "gzip"); // Client must understood what we're sending him
                printWriter.write("Hello world from gzip encoded html"); // What is sending?
            }
    
        } else {
            resp.getWriter().write("Can't encode html to gzip :(");
        }
    
    }
    

提交回复
热议问题