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.impl.entity;
29
30 import org.apache.http.Header;
31 import org.apache.http.HttpException;
32 import org.apache.http.HttpMessage;
33 import org.apache.http.HttpVersion;
34 import org.apache.http.ProtocolException;
35 import org.apache.http.annotation.ThreadingBehavior;
36 import org.apache.http.annotation.Contract;
37 import org.apache.http.entity.ContentLengthStrategy;
38 import org.apache.http.protocol.HTTP;
39 import org.apache.http.util.Args;
40
41
42
43
44
45
46
47
48
49
50
51 @Contract(threading = ThreadingBehavior.IMMUTABLE)
52 public class StrictContentLengthStrategy implements ContentLengthStrategy {
53
54 public static final StrictContentLengthStrategytrategy.html#StrictContentLengthStrategy">StrictContentLengthStrategy INSTANCE = new StrictContentLengthStrategy();
55
56 private final int implicitLen;
57
58
59
60
61
62
63
64
65
66 public StrictContentLengthStrategy(final int implicitLen) {
67 super();
68 this.implicitLen = implicitLen;
69 }
70
71
72
73
74
75 public StrictContentLengthStrategy() {
76 this(IDENTITY);
77 }
78
79 @Override
80 public long determineLength(final HttpMessage message) throws HttpException {
81 Args.notNull(message, "HTTP message");
82
83
84
85 final Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING);
86 if (transferEncodingHeader != null) {
87 final String s = transferEncodingHeader.getValue();
88 if (HTTP.CHUNK_CODING.equalsIgnoreCase(s)) {
89 if (message.getProtocolVersion().lessEquals(HttpVersion.HTTP_1_0)) {
90 throw new ProtocolException(
91 "Chunked transfer encoding not allowed for " +
92 message.getProtocolVersion());
93 }
94 return CHUNKED;
95 } else if (HTTP.IDENTITY_CODING.equalsIgnoreCase(s)) {
96 return IDENTITY;
97 } else {
98 throw new ProtocolException(
99 "Unsupported transfer encoding: " + s);
100 }
101 }
102 final Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN);
103 if (contentLengthHeader != null) {
104 final String s = contentLengthHeader.getValue();
105 try {
106 final long len = Long.parseLong(s);
107 if (len < 0) {
108 throw new ProtocolException("Negative content length: " + s);
109 }
110 return len;
111 } catch (final NumberFormatException e) {
112 throw new ProtocolException("Invalid content length: " + s);
113 }
114 }
115 return this.implicitLen;
116 }
117
118 }