1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.hc.core5.http.protocol;
29
30 import java.io.IOException;
31
32 import org.apache.hc.core5.annotation.Contract;
33 import org.apache.hc.core5.annotation.ThreadingBehavior;
34 import org.apache.hc.core5.http.EntityDetails;
35 import org.apache.hc.core5.http.HeaderElements;
36 import org.apache.hc.core5.http.HttpException;
37 import org.apache.hc.core5.http.HttpHeaders;
38 import org.apache.hc.core5.http.HttpResponse;
39 import org.apache.hc.core5.http.HttpResponseInterceptor;
40 import org.apache.hc.core5.http.HttpStatus;
41 import org.apache.hc.core5.http.HttpVersion;
42 import org.apache.hc.core5.http.ProtocolException;
43 import org.apache.hc.core5.http.ProtocolVersion;
44 import org.apache.hc.core5.http.message.MessageSupport;
45 import org.apache.hc.core5.util.Args;
46
47
48
49
50
51
52
53
54
55
56
57 @Contract(threading = ThreadingBehavior.IMMUTABLE)
58 public class ResponseContent implements HttpResponseInterceptor {
59
60 private final boolean overwrite;
61
62
63
64
65
66
67 public ResponseContent() {
68 this(false);
69 }
70
71
72
73
74
75
76
77
78
79
80
81
82 public ResponseContent(final boolean overwrite) {
83 super();
84 this.overwrite = overwrite;
85 }
86
87
88
89
90
91
92
93
94 @Override
95 public void process(final HttpResponse response, final EntityDetails entity, final HttpContext context)
96 throws HttpException, IOException {
97 Args.notNull(response, "HTTP response");
98 if (this.overwrite) {
99 response.removeHeaders(HttpHeaders.TRANSFER_ENCODING);
100 response.removeHeaders(HttpHeaders.CONTENT_LENGTH);
101 } else {
102 if (response.containsHeader(HttpHeaders.TRANSFER_ENCODING)) {
103 throw new ProtocolException("Transfer-encoding header already present");
104 }
105 if (response.containsHeader(HttpHeaders.CONTENT_LENGTH)) {
106 throw new ProtocolException("Content-Length header already present");
107 }
108 }
109 final ProtocolVersion ver = context.getProtocolVersion();
110 if (entity != null) {
111 final long len = entity.getContentLength();
112 if (len >= 0 && !entity.isChunked()) {
113 response.addHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(entity.getContentLength()));
114 } else if (ver.greaterEquals(HttpVersion.HTTP_1_1)) {
115 response.addHeader(HttpHeaders.TRANSFER_ENCODING, HeaderElements.CHUNKED_ENCODING);
116 MessageSupport.addTrailerHeader(response, entity);
117 }
118 MessageSupport.addContentTypeHeader(response, entity);
119 MessageSupport.addContentEncodingHeader(response, entity);
120 } else {
121 final int status = response.getCode();
122 if (status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_NOT_MODIFIED) {
123 response.addHeader(HttpHeaders.CONTENT_LENGTH, "0");
124 }
125 }
126 }
127
128 }