View Javadoc
1   /*
2    * Copyright 2002-2014 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.http.client;
18  
19  import java.io.ByteArrayOutputStream;
20  import java.io.IOException;
21  import java.io.OutputStream;
22  
23  import org.springframework.http.HttpHeaders;
24  
25  /**
26   * Base implementation of {@link ClientHttpRequest} that buffers output
27   * in a byte array before sending it over the wire.
28   *
29   * @author Arjen Poutsma
30   * @since 3.0.6
31   */
32  abstract class AbstractBufferingClientHttpRequest extends AbstractClientHttpRequest {
33  
34  	private ByteArrayOutputStream bufferedOutput = new ByteArrayOutputStream(1024);
35  
36  
37  	@Override
38  	protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
39  		return this.bufferedOutput;
40  	}
41  
42  	@Override
43  	protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
44  		byte[] bytes = this.bufferedOutput.toByteArray();
45  		if (headers.getContentLength() == -1) {
46  			headers.setContentLength(bytes.length);
47  		}
48  		ClientHttpResponse result = executeInternal(headers, bytes);
49  		this.bufferedOutput = null;
50  		return result;
51  	}
52  
53  	/**
54  	 * Abstract template method that writes the given headers and content to the HTTP request.
55  	 * @param headers the HTTP headers
56  	 * @param bufferedOutput the body content
57  	 * @return the response object for the executed request
58  	 */
59  	protected abstract ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput)
60  			throws IOException;
61  
62  
63  }