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.HttpEntityEnclosingRequest;
34 import org.apache.http.HttpException;
35 import org.apache.http.HttpRequest;
36 import org.apache.http.HttpRequestInterceptor;
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 RequestContent implements HttpRequestInterceptor {
56
57 private final boolean overwrite;
58
59
60
61
62
63
64 public RequestContent() {
65 this(false);
66 }
67
68
69
70
71
72
73
74
75
76
77
78
79 public RequestContent(final boolean overwrite) {
80 super();
81 this.overwrite = overwrite;
82 }
83
84 @Override
85 public void process(final HttpRequest request, final HttpContext context)
86 throws HttpException, IOException {
87 Args.notNull(request, "HTTP request");
88 if (request instanceof HttpEntityEnclosingRequest) {
89 if (this.overwrite) {
90 request.removeHeaders(HTTP.TRANSFER_ENCODING);
91 request.removeHeaders(HTTP.CONTENT_LEN);
92 } else {
93 if (request.containsHeader(HTTP.TRANSFER_ENCODING)) {
94 throw new ProtocolException("Transfer-encoding header already present");
95 }
96 if (request.containsHeader(HTTP.CONTENT_LEN)) {
97 throw new ProtocolException("Content-Length header already present");
98 }
99 }
100 final ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
101 final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
102 if (entity == null) {
103 request.addHeader(HTTP.CONTENT_LEN, "0");
104 return;
105 }
106
107 if (entity.isChunked() || entity.getContentLength() < 0) {
108 if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
109 throw new ProtocolException(
110 "Chunked transfer encoding not allowed for " + ver);
111 }
112 request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);
113 } else {
114 request.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength()));
115 }
116
117 if (entity.getContentType() != null && !request.containsHeader(
118 HTTP.CONTENT_TYPE )) {
119 request.addHeader(entity.getContentType());
120 }
121
122 if (entity.getContentEncoding() != null && !request.containsHeader(
123 HTTP.CONTENT_ENCODING)) {
124 request.addHeader(entity.getContentEncoding());
125 }
126 }
127 }
128
129 }