001/*
002 * Copyright 2002-2018 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.http.client;
018
019import java.io.IOException;
020import java.net.URI;
021
022import org.springframework.http.HttpMethod;
023
024/**
025 * Wrapper for a {@link ClientHttpRequestFactory} that buffers
026 * all outgoing and incoming streams in memory.
027 *
028 * <p>Using this wrapper allows for multiple reads of the
029 * {@linkplain ClientHttpResponse#getBody() response body}.
030 *
031 * @author Arjen Poutsma
032 * @since 3.1
033 */
034public class BufferingClientHttpRequestFactory extends AbstractClientHttpRequestFactoryWrapper {
035
036        /**
037         * Create a buffering wrapper for the given {@link ClientHttpRequestFactory}.
038         * @param requestFactory the target request factory to wrap
039         */
040        public BufferingClientHttpRequestFactory(ClientHttpRequestFactory requestFactory) {
041                super(requestFactory);
042        }
043
044
045        @Override
046        protected ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod, ClientHttpRequestFactory requestFactory)
047                        throws IOException {
048
049                ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod);
050                if (shouldBuffer(uri, httpMethod)) {
051                        return new BufferingClientHttpRequestWrapper(request);
052                }
053                else {
054                        return request;
055                }
056        }
057
058        /**
059         * Indicates whether the request/response exchange for the given URI and method
060         * should be buffered in memory.
061         * <p>The default implementation returns {@code true} for all URIs and methods.
062         * Subclasses can override this method to change this behavior.
063         * @param uri the URI
064         * @param httpMethod the method
065         * @return {@code true} if the exchange should be buffered; {@code false} otherwise
066         */
067        protected boolean shouldBuffer(URI uri, HttpMethod httpMethod) {
068                return true;
069        }
070
071}