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.http.protocol;
29
30 import java.io.IOException;
31
32 import org.apache.http.HttpEntity;
33 import org.apache.http.HttpException;
34 import org.apache.http.HttpResponse;
35 import org.apache.http.HttpResponseInterceptor;
36 import org.apache.http.HttpStatus;
37 import org.apache.http.HttpVersion;
38 import org.apache.http.ProtocolException;
39 import org.apache.http.ProtocolVersion;
40 import org.apache.http.annotation.ThreadingBehavior;
41 import org.apache.http.annotation.Contract;
42 import org.apache.http.util.Args;
43
44
45
46
47
48
49
50
51
52
53
54 @Contract(threading = ThreadingBehavior.IMMUTABLE)
55 public class ResponseContent implements HttpResponseInterceptor {
56
57 private final boolean overwrite;
58
59
60
61
62
63
64 public ResponseContent() {
65 this(false);
66 }
67
68
69
70
71
72
73
74
75
76
77
78
79 public ResponseContent(final boolean overwrite) {
80 super();
81 this.overwrite = overwrite;
82 }
83
84
85
86
87
88
89
90
91 @Override
92 public void process(final HttpResponse response, final HttpContext context)
93 throws HttpException, IOException {
94 Args.notNull(response, "HTTP response");
95 if (this.overwrite) {
96 response.removeHeaders(HTTP.TRANSFER_ENCODING);
97 response.removeHeaders(HTTP.CONTENT_LEN);
98 } else {
99 if (response.containsHeader(HTTP.TRANSFER_ENCODING)) {
100 throw new ProtocolException("Transfer-encoding header already present");
101 }
102 if (response.containsHeader(HTTP.CONTENT_LEN)) {
103 throw new ProtocolException("Content-Length header already present");
104 }
105 }
106 final ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
107 final HttpEntity entity = response.getEntity();
108 if (entity != null) {
109 final long len = entity.getContentLength();
110 if (entity.isChunked() && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
111 response.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);
112 } else if (len >= 0) {
113 response.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength()));
114 }
115
116 if (entity.getContentType() != null && !response.containsHeader(
117 HTTP.CONTENT_TYPE )) {
118 response.addHeader(entity.getContentType());
119 }
120
121 if (entity.getContentEncoding() != null && !response.containsHeader(
122 HTTP.CONTENT_ENCODING)) {
123 response.addHeader(entity.getContentEncoding());
124 }
125 } else {
126 final int status = response.getStatusLine().getStatusCode();
127 if (status != HttpStatus.SC_NO_CONTENT
128 && status != HttpStatus.SC_NOT_MODIFIED
129 && status != HttpStatus.SC_RESET_CONTENT) {
130 response.addHeader(HTTP.CONTENT_LEN, "0");
131 }
132 }
133 }
134
135 }