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
20 import static io.netty.handler.codec.http.HttpConstants.*;
21
22
23
24
25
26 public class HttpResponseEncoder extends HttpObjectEncoder<HttpResponse> {
27
28 @Override
29 public boolean acceptOutboundMessage(Object msg) throws Exception {
30 return super.acceptOutboundMessage(msg) && !(msg instanceof HttpRequest);
31 }
32
33 @Override
34 protected void encodeInitialLine(ByteBuf buf, HttpResponse response) throws Exception {
35 response.getProtocolVersion().encode(buf);
36 buf.writeByte(SP);
37 response.getStatus().encode(buf);
38 buf.writeBytes(CRLF);
39 }
40
41 @Override
42 protected void sanitizeHeadersBeforeEncode(HttpResponse msg, boolean isAlwaysEmpty) {
43 if (isAlwaysEmpty) {
44 int status = msg.getStatus().code();
45 if ((status >= 100 && status <= 199) ||
46 status == HttpResponseStatus.NO_CONTENT.code()) {
47
48
49
50 msg.headers().remove(HttpHeaders.Names.CONTENT_LENGTH);
51
52
53
54 msg.headers().remove(HttpHeaders.Names.TRANSFER_ENCODING);
55 }
56 }
57 }
58
59 @Override
60 protected boolean isContentAlwaysEmpty(HttpResponse msg) {
61
62
63 int status = msg.getStatus().code();
64
65 if (status >= 100 && status <= 199) {
66
67 if (status == HttpResponseStatus.SWITCHING_PROTOCOLS.code()) {
68
69
70
71 return msg.headers().contains(HttpHeaders.Names.SEC_WEBSOCKET_VERSION);
72 }
73 return true;
74 }
75 return status == HttpResponseStatus.NO_CONTENT.code() ||
76 status == HttpResponseStatus.NOT_MODIFIED.code();
77 }
78 }