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.HeaderElement;
32 import org.apache.http.HttpException;
33 import org.apache.http.HttpMessage;
34 import org.apache.http.ParseException;
35 import org.apache.http.ProtocolException;
36 import org.apache.http.annotation.ThreadingBehavior;
37 import org.apache.http.annotation.Contract;
38 import org.apache.http.entity.ContentLengthStrategy;
39 import org.apache.http.protocol.HTTP;
40 import org.apache.http.util.Args;
41
42
43
44
45
46
47
48
49
50
51 @Contract(threading = ThreadingBehavior.IMMUTABLE)
52 public class LaxContentLengthStrategy implements ContentLengthStrategy {
53
54 public static final LaxContentLengthStrategytrategy.html#LaxContentLengthStrategy">LaxContentLengthStrategy INSTANCE = new LaxContentLengthStrategy();
55
56 private final int implicitLen;
57
58
59
60
61
62
63
64
65
66 public LaxContentLengthStrategy(final int implicitLen) {
67 super();
68 this.implicitLen = implicitLen;
69 }
70
71
72
73
74
75 public LaxContentLengthStrategy() {
76 this(IDENTITY);
77 }
78
79 @Override
80 public long determineLength(final HttpMessage message) throws HttpException {
81 Args.notNull(message, "HTTP message");
82
83 final Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING);
84
85
86 if (transferEncodingHeader != null) {
87 final HeaderElement[] encodings;
88 try {
89 encodings = transferEncodingHeader.getElements();
90 } catch (final ParseException px) {
91 throw new ProtocolException
92 ("Invalid Transfer-Encoding header value: " +
93 transferEncodingHeader, px);
94 }
95
96 final int len = encodings.length;
97 if (HTTP.IDENTITY_CODING.equalsIgnoreCase(transferEncodingHeader.getValue())) {
98 return IDENTITY;
99 } else if ((len > 0) && (HTTP.CHUNK_CODING.equalsIgnoreCase(
100 encodings[len - 1].getName()))) {
101 return CHUNKED;
102 } else {
103 return IDENTITY;
104 }
105 }
106 final Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN);
107 if (contentLengthHeader != null) {
108 long contentLen = -1;
109 final Header[] headers = message.getHeaders(HTTP.CONTENT_LEN);
110 for (int i = headers.length - 1; i >= 0; i--) {
111 final Header header = headers[i];
112 try {
113 contentLen = Long.parseLong(header.getValue());
114 break;
115 } catch (final NumberFormatException ignore) {
116 }
117
118 }
119 return contentLen >= 0 ? contentLen : IDENTITY;
120 }
121 return this.implicitLen;
122 }
123
124 }