FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(json.getBytes()));
// 下面的把 gzip 申明删了就是 Ok 的,添加了就不能访问了
response.headers().set(CONTENT_ENCODING, HttpHeaderValues.GZIP);
response.headers().set(TRANSFER_ENCODING,HttpHeaderValues.CHUNKED);
if (!keepAlive) {
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
} else {
response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
ctx.write(response);
}
服务器上 nginx 调用 gzip 压缩功能正常。现在是直接用 netty 的话,怎么就会不抛异常,也不输出错误。
暂时把压缩放到 nginx 里面去做了。
时隔半年,解决了,我的版本是netty 5.0
。如果谁遇到了同样的问题,希望对大家有帮助。
public class ServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpServerCodec());
p.addLast(new HttpContentCompressor(1));
p.addLast(new ServerHandler()); // ServerHandler extends ChannelHandlerAdapter
}
}
我自己做了一个稍微详细的笔记 http://mengkang.net/611.html