本篇我们来讲解HttpResponseEncoder如何将响应体FullHttpResponse转化成ByteBuf。
先来看下Http响应报文
![34c532d2732eaa04424166d5a395a0aa.png](https://i-blog.csdnimg.cn/blog_migrate/b74a25ab3e27ebc34b419f53a0f87e8b.jpeg)
HttpResponseEncoder就是按照这样的格式将数据解析成http响应报文。
HttpResponseEncoder核心方法
protected void encode(ChannelHandlerContext ctx, Object msg, List out) throws Exception { ByteBuf buf = null; if (msg instanceof HttpMessage) { if (state != ST_INIT) { throw new IllegalStateException("unexpected message type: " + StringUtil.simpleClassName(msg) + ", state: " + state); } @SuppressWarnings({ "unchecked", "CastConflictsWithInstanceof" }) H m = (H) msg; buf = ctx.alloc().buffer((int) headersEncodedSizeAccumulator); // Encode the message. encodeInitialLine(buf, m); state = isContentAlwaysEmpty(m) ? ST_CONTENT_ALWAYS_EMPTY : HttpUtil.isTransferEncodingChunked(m) ? ST_CONTENT_CHUNK : ST_CONTENT_NON_CHUNK; sanitizeHeadersBeforeEncode(m, state == ST_CONTENT_ALWAYS_EMPTY); encodeHeaders(m.headers(), buf); ByteBufUtil.writeShortBE(buf, CRLF_SHORT);