【问题标题】:Serve an already-gzipped response from a Servlet从 Servlet 提供已经压缩过的响应
【发布时间】:2015-04-09 21:59:45
【问题描述】:

我的应用程序中有一个压缩过的 JSON 资源,我想通过 servlet 提供它。浏览器不同意确切的原因,但它们都不会真正加载我的内容。这段代码看起来有问题吗?

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");
    }
}

【问题讨论】:

    标签: java servlets gzip


    【解决方案1】:

    我认为您正在寻找的答案可在此线程中已接受答案的链接中找到 - Serve Gzipped content with Java Servlets

    这包括来自 O'Reilly 网站的一个工作示例。

    但是,我会质疑您是否需要引入这种交叉卷曲问题并手动 gzip 内容。假设您使用的是 Apache 或其分支,我建议您查看mod_deflate,它是可配置且功能强大的,让您无需编写用于 gzip 响应的样板代码。

    【讨论】:

      猜你喜欢
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 2010-10-31
      • 2012-02-12
      • 1970-01-01
      相关资源
      最近更新 更多