java - 如何使用 Netty deflator 压缩发送到浏览器的响应

标签 java gzip netty

我正在尝试使用netty中可用的压缩器,在 channel 管道中添加了以下行

pipeline.addLast("gzip", new HttpContentCompressor());

我将响应 header “Content-Encoding”设置为“gzip”

我的问题是如何设置内容,我尝试了以下

response.setContent(ChannelBuffers.copiedBuffer(responseText, CharsetUtil.UTF_8));

where responseText --> 我想要发送到浏览器的字符串。

我收到一个错误,内容不是 gzip 流

org.jboss.netty.handler.codec.embedder.CodecEmbedderException: org.jboss.netty.handler.codec.compression.CompressionException: decompression failure (-3): not a gzip stream

我应该 gzip responseText 然后执行 setContent(gzippedResponse) 吗?或者我在这里遗漏了什么?

最佳答案

  • 您无需将响应 header “Content-Encoding”设置为“gzip”。 Netty 为你做这件事。请参阅继承自 HttpContentCompressorHttpContentEncoder

  • 您不需要 gzip responseText

  • 您的管道应如下所示:

    // Create a default pipeline implementation.
    ChannelPipeline pipeline = pipeline();
    
    // Decodes ChannelBuffer into HTTP Request message
    pipeline.addLast("decoder", new HttpRequestDecoder());
    
    // Encodes HTTTPRequest message to ChannelBuffer
    pipeline.addLast("encoder", new HttpResponseEncoder());
    
    // Compress
    pipeline.addLast("deflater", new HttpContentCompressor(1));
    
    // Handler to dispatch processing to our services
    pipeline.addLast("handler", new YourHttpRequestHandler());
    

关于java - 如何使用 Netty deflator 压缩发送到浏览器的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8605519/

相关文章:

java - 写入客户端 channel 时出现异常 java.nio.channels.ClosedChannelException

java - eclipse + GAE : Properties changes and therefor problems with deploy

java - Android:如何避免点击通知调用 onCreate()

Ruby Net::HTTP 不解码 gzip?

javascript - 如何在 javascript 中解压缩 gzip 文件?

java - 从其他添加处理程序时 Netty ChannelActive 不起作用

java - findElement(By) 和 findElementBy() 有什么区别?

带有自动装箱的三元运算符中的Java NPE?

java - 获取未压缩的 gzip 文件的大小,而压缩文件的大小可从服务器获得

java - 如果客户端从不发送 FIN 数据包关闭连接,连接是否超时?