}
if (message == null) {
throw new IllegalArgumentException("HTTP message may not be null");
}
BasicHttpEntity entity = new BasicHttpEntity();
HttpParams params = message.getParams();
boolean strict = params.isParameterTrue(HttpProtocolParams.STRICT_TRANSFER_ENCODING);
Header contentTypeHeader = message.getFirstHeader(HTTP.CONTENT_TYPE);
Header contentEncodingHeader = message.getFirstHeader(HTTP.CONTENT_ENCODING);
Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING);
Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN);
// We use Transfer-Encoding if present and ignore Content-Length.
// RFC2616, 4.4 item number 3
if (transferEncodingHeader != null) {
HeaderElement[] encodings = transferEncodingHeader.getElements();
if (strict) {
// Currently only chunk and identity are supported
for (int i = 0; i < encodings.length; i++) {
String encoding = encodings[i].getName();
if (encoding != null && !encoding.equals("")
&& !encoding.equalsIgnoreCase(HTTP.CHUNK_CODING)
&& !encoding.equalsIgnoreCase(HTTP.IDENTITY_CODING)) {
throw new ProtocolException("Unsupported transfer encoding: " + encoding);
}
}
}
// The chunked encoding must be the last one applied RFC2616, 14.41
int len = encodings.length;
if (HTTP.IDENTITY_CODING.equalsIgnoreCase(transferEncodingHeader.getValue())) {
entity.setChunked(false);
entity.setContentLength(-1);
entity.setContent(new HttpDataInputStream(datareceiver));
} else if ((len > 0) && (HTTP.CHUNK_CODING.equalsIgnoreCase(
encodings[len - 1].getName()))) {
entity.setChunked(true);
entity.setContentLength(-1);
entity.setContent(new ChunkedInputStream(datareceiver));
} else {
if (strict) {
throw new ProtocolException("Chunk-encoding must be the last one applied");
}
entity.setChunked(false);
entity.setContentLength(-1);
entity.setContent(new HttpDataInputStream(datareceiver));
}
} else if (contentLengthHeader != null) {
long contentlen = -1;
Header[] headers = message.getHeaders(HTTP.CONTENT_LEN);
if (strict && headers.length > 1) {
throw new ProtocolException("Multiple content length headers");
}
for (int i = headers.length - 1; i >= 0; i--) {
Header header = headers[i];
try {
contentlen = Long.parseLong(header.getValue());
break;
} catch (NumberFormatException e) {
if (strict) {
throw new ProtocolException("Invalid content length: " + header.getValue());
}
}
// See if we can have better luck with another header, if present
}
entity.setChunked(false);
entity.setContentLength(contentlen);
if (contentlen >= 0) {
entity.setContent(new ContentLengthInputStream(datareceiver, contentlen));
} else {
entity.setContent(new HttpDataInputStream(datareceiver));
}
} else {
entity.setChunked(false);
entity.setContentLength(-1);
entity.setContent(new HttpDataInputStream(datareceiver));
}
if (contentTypeHeader != null) {
entity.setContentType(contentTypeHeader);
}
if (contentEncodingHeader != null) {
entity.setContentEncoding(contentEncodingHeader);
}
return entity;
}