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.HttpRequest;
39 import org.apache.hc.core5.http.HttpRequestInterceptor;
40 import org.apache.hc.core5.http.HttpVersion;
41 import org.apache.hc.core5.http.Method;
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 RequestContent implements HttpRequestInterceptor {
59
60 private final boolean overwrite;
61
62
63
64
65
66
67 public RequestContent() {
68 this(false);
69 }
70
71
72
73
74
75
76
77
78
79
80
81
82 public RequestContent(final boolean overwrite) {
83 super();
84 this.overwrite = overwrite;
85 }
86
87 @Override
88 public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context)
89 throws HttpException, IOException {
90 Args.notNull(request, "HTTP request");
91 final String method = request.getMethod();
92 if (Method.TRACE.isSame(method) && entity != null) {
93 throw new ProtocolException("TRACE request may not enclose an entity");
94 }
95 if (this.overwrite) {
96 request.removeHeaders(HttpHeaders.TRANSFER_ENCODING);
97 request.removeHeaders(HttpHeaders.CONTENT_LENGTH);
98 } else {
99 if (request.containsHeader(HttpHeaders.TRANSFER_ENCODING)) {
100 throw new ProtocolException("Transfer-encoding header already present");
101 }
102 if (request.containsHeader(HttpHeaders.CONTENT_LENGTH)) {
103 throw new ProtocolException("Content-Length header already present");
104 }
105 }
106 if (entity != null) {
107 final ProtocolVersion ver = context.getProtocolVersion();
108
109 if (entity.isChunked() || entity.getContentLength() < 0) {
110 if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
111 throw new ProtocolException(
112 "Chunked transfer encoding not allowed for " + ver);
113 }
114 request.addHeader(HttpHeaders.TRANSFER_ENCODING, HeaderElements.CHUNKED_ENCODING);
115 MessageSupport.addTrailerHeader(request, entity);
116 } else {
117 request.addHeader(HttpHeaders.CONTENT_LENGTH, Long.toString(entity.getContentLength()));
118 }
119 MessageSupport.addContentTypeHeader(request, entity);
120 MessageSupport.addContentEncodingHeader(request, entity);
121 }
122 }
123
124 }