001/*
002 * ====================================================================
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *   http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing,
014 * software distributed under the License is distributed on an
015 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
016 * KIND, either express or implied.  See the License for the
017 * specific language governing permissions and limitations
018 * under the License.
019 * ====================================================================
020 *
021 * This software consists of voluntary contributions made by many
022 * individuals on behalf of the Apache Software Foundation.  For more
023 * information on the Apache Software Foundation, please see
024 * <http://www.apache.org/>.
025 *
026 */
027
028package org.apache.http.protocol;
029
030import java.io.IOException;
031
032import org.apache.http.HttpEntity;
033import org.apache.http.HttpEntityEnclosingRequest;
034import org.apache.http.HttpException;
035import org.apache.http.HttpRequest;
036import org.apache.http.HttpRequestInterceptor;
037import org.apache.http.HttpVersion;
038import org.apache.http.ProtocolException;
039import org.apache.http.ProtocolVersion;
040import org.apache.http.annotation.ThreadingBehavior;
041import org.apache.http.annotation.Contract;
042import org.apache.http.util.Args;
043
044/**
045 * RequestContent is the most important interceptor for outgoing requests.
046 * It is responsible for delimiting content length by adding
047 * {@code Content-Length} or {@code Transfer-Content} headers based
048 * on the properties of the enclosed entity and the protocol version.
049 * This interceptor is required for correct functioning of client side protocol
050 * processors.
051 *
052 * @since 4.0
053 */
054@Contract(threading = ThreadingBehavior.IMMUTABLE)
055public class RequestContent implements HttpRequestInterceptor {
056
057    private final boolean overwrite;
058
059    /**
060     * Default constructor. The {@code Content-Length} or {@code Transfer-Encoding}
061     * will cause the interceptor to throw {@link ProtocolException} if already present in the
062     * response message.
063     */
064    public RequestContent() {
065        this(false);
066    }
067
068    /**
069     * Constructor that can be used to fine-tune behavior of this interceptor.
070     *
071     * @param overwrite If set to {@code true} the {@code Content-Length} and
072     * {@code Transfer-Encoding} headers will be created or updated if already present.
073     * If set to {@code false} the {@code Content-Length} and
074     * {@code Transfer-Encoding} headers will cause the interceptor to throw
075     * {@link ProtocolException} if already present in the response message.
076     *
077     * @since 4.2
078     */
079     public RequestContent(final boolean overwrite) {
080         super();
081         this.overwrite = overwrite;
082    }
083
084    @Override
085    public void process(final HttpRequest request, final HttpContext context)
086            throws HttpException, IOException {
087        Args.notNull(request, "HTTP request");
088        if (request instanceof HttpEntityEnclosingRequest) {
089            if (this.overwrite) {
090                request.removeHeaders(HTTP.TRANSFER_ENCODING);
091                request.removeHeaders(HTTP.CONTENT_LEN);
092            } else {
093                if (request.containsHeader(HTTP.TRANSFER_ENCODING)) {
094                    throw new ProtocolException("Transfer-encoding header already present");
095                }
096                if (request.containsHeader(HTTP.CONTENT_LEN)) {
097                    throw new ProtocolException("Content-Length header already present");
098                }
099            }
100            final ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
101            final HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
102            if (entity == null) {
103                request.addHeader(HTTP.CONTENT_LEN, "0");
104                return;
105            }
106            // Must specify a transfer encoding or a content length
107            if (entity.isChunked() || entity.getContentLength() < 0) {
108                if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
109                    throw new ProtocolException(
110                            "Chunked transfer encoding not allowed for " + ver);
111                }
112                request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);
113            } else {
114                request.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength()));
115            }
116            // Specify a content type if known
117            if (entity.getContentType() != null && !request.containsHeader(
118                    HTTP.CONTENT_TYPE )) {
119                request.addHeader(entity.getContentType());
120            }
121            // Specify a content encoding if known
122            if (entity.getContentEncoding() != null && !request.containsHeader(
123                    HTTP.CONTENT_ENCODING)) {
124                request.addHeader(entity.getContentEncoding());
125            }
126        }
127    }
128
129}