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.impl;
29
30 import org.apache.hc.core5.annotation.Contract;
31 import org.apache.hc.core5.annotation.ThreadingBehavior;
32 import org.apache.hc.core5.http.ContentLengthStrategy;
33 import org.apache.hc.core5.http.Header;
34 import org.apache.hc.core5.http.HeaderElements;
35 import org.apache.hc.core5.http.HttpException;
36 import org.apache.hc.core5.http.HttpHeaders;
37 import org.apache.hc.core5.http.HttpMessage;
38 import org.apache.hc.core5.http.NotImplementedException;
39 import org.apache.hc.core5.http.ProtocolException;
40 import org.apache.hc.core5.util.Args;
41
42
43
44
45
46
47
48
49
50
51
52 @Contract(threading = ThreadingBehavior.IMMUTABLE)
53 public class DefaultContentLengthStrategy implements ContentLengthStrategy {
54
55 public static final DefaultContentLengthStrategy INSTANCE = new DefaultContentLengthStrategy();
56
57
58
59
60
61 public DefaultContentLengthStrategy() {
62 }
63
64 @Override
65 public long determineLength(final HttpMessage message) throws HttpException {
66 Args.notNull(message, "HTTP message");
67
68
69
70 final Header transferEncodingHeader = message.getFirstHeader(HttpHeaders.TRANSFER_ENCODING);
71 if (transferEncodingHeader != null) {
72 final String headerValue = transferEncodingHeader.getValue();
73 if (HeaderElements.CHUNKED_ENCODING.equalsIgnoreCase(headerValue)) {
74 return CHUNKED;
75 }
76 throw new NotImplementedException("Unsupported transfer encoding: " + headerValue);
77 }
78 if (message.countHeaders(HttpHeaders.CONTENT_LENGTH) > 1) {
79 throw new ProtocolException("Multiple Content-Length headers");
80 }
81 final Header contentLengthHeader = message.getFirstHeader(HttpHeaders.CONTENT_LENGTH);
82 if (contentLengthHeader != null) {
83 final String s = contentLengthHeader.getValue();
84 try {
85 final long len = Long.parseLong(s);
86 if (len < 0) {
87 throw new ProtocolException("Negative content length: " + s);
88 }
89 return len;
90 } catch (final NumberFormatException e) {
91 throw new ProtocolException("Invalid content length: " + s);
92 }
93 }
94 return UNDEFINED;
95 }
96
97 }