【问题标题】:reading gzipped request in servlet在 servlet 中读取压缩请求
【发布时间】:2013-07-14 15:11:41
【问题描述】:

我在一项非常简单的任务中遗漏了一些东西:我必须检查传入的请求输入流是否已压缩并解压缩其内容。这不使用内容类型。 我想过这样的事情:

检查请求是否被压缩:

private boolean isGZIPed( HttpServletRequest request )
{
    boolean isGziped = false;
    try
    {
        PushbackInputStream pb = new PushbackInputStream( request.getInputStream(), 2 );
        byte[] signature = new byte[2];
        pb.read( signature );
        pb.unread( signature );
        int head = ( (int)signature[0] & 0xff ) | ( ( signature[1] << 8 ) & 0xff00 );
        isGziped = GZIPInputStream.GZIP_MAGIC == head;
    }
    catch( Exception ioe )
    {
        logger.error(ioe);
    }
    return isGziped;
}

如果确实是 gzip 则取消压缩:

if(isGziped(request) 
{
    GZIPInputStream gzis = new GZIPInputStream( request.getInputStream() );
    InputStreamReader reader = new InputStreamReader( gzis );
    ...
}

我的问题是 new GZIPInputStream(request.getInputStream()) 总是抛出“不是 gzip 格式”异常。我错过了什么?

【问题讨论】:

    标签: java servlets gzip gzipinputstream


    【解决方案1】:

    当您从推回输入流中读取数据时,您会从请求输入流中删除数据。 “未读”字节仅将它们推送到推回流,而不是底层流。

    您应该使用推回流创建GZIPInputStream,以便可以重新读取您读取和推回的字节:

    GZIPInputStream gzis = new GZIPInputStream( pb );
    

    这意味着必须在适当的范围内声明推回流。

    【讨论】:

      猜你喜欢
      • 2013-12-28
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 2011-03-26
      • 2011-07-01
      • 2019-01-27
      • 2016-03-15
      • 2011-12-09
      相关资源
      最近更新 更多