1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.http;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.ByteBufUtil;
20
21 import static io.netty.handler.codec.http.HttpConstants.*;
22
23
24
25
26
27 public class HttpResponseEncoder extends HttpObjectEncoder<HttpResponse> {
28
29 @Override
30 public boolean acceptOutboundMessage(Object msg) throws Exception {
31
32
33
34
35
36
37 final Class<?> msgClass = msg.getClass();
38 if (msgClass == DefaultFullHttpResponse.class || msgClass == DefaultHttpResponse.class) {
39 return true;
40 }
41 return super.acceptOutboundMessage(msg) && !(msg instanceof HttpRequest);
42 }
43
44 @Override
45 protected void encodeInitialLine(ByteBuf buf, HttpResponse response) throws Exception {
46 response.protocolVersion().encode(buf);
47 buf.writeByte(SP);
48 response.status().encode(buf);
49 ByteBufUtil.writeShortBE(buf, CRLF_SHORT);
50 }
51
52 @Override
53 protected void sanitizeHeadersBeforeEncode(HttpResponse msg, boolean isAlwaysEmpty) {
54 if (isAlwaysEmpty) {
55 HttpResponseStatus status = msg.status();
56 if (status.codeClass() == HttpStatusClass.INFORMATIONAL ||
57 status.code() == HttpResponseStatus.NO_CONTENT.code()) {
58
59
60
61 msg.headers().remove(HttpHeaderNames.CONTENT_LENGTH);
62
63
64
65 msg.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
66 } else if (status.code() == HttpResponseStatus.RESET_CONTENT.code()) {
67
68
69 msg.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
70
71
72
73 msg.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
74 }
75 }
76 }
77
78 @Override
79 protected boolean isContentAlwaysEmpty(HttpResponse msg) {
80
81
82 HttpResponseStatus status = msg.status();
83
84 if (status.codeClass() == HttpStatusClass.INFORMATIONAL) {
85
86 if (status.code() == HttpResponseStatus.SWITCHING_PROTOCOLS.code()) {
87
88
89
90 return msg.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_VERSION);
91 }
92 return true;
93 }
94 return status.code() == HttpResponseStatus.NO_CONTENT.code() ||
95 status.code() == HttpResponseStatus.NOT_MODIFIED.code() ||
96 status.code() == HttpResponseStatus.RESET_CONTENT.code();
97 }
98 }