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.IOException;
20  import java.io.InputStream;
21  import java.net.HttpURLConnection;
22  
23  import org.springframework.http.HttpHeaders;
24  import org.springframework.util.StringUtils;
25  
26  /**
27   * {@link ClientHttpResponse} implementation that uses standard JDK facilities.
28   * Obtained via {@link SimpleBufferingClientHttpRequest#execute()} and
29   * {@link SimpleStreamingClientHttpRequest#execute()}.
30   *
31   * @author Arjen Poutsma
32   * @since 3.0
33   */
34  final class SimpleClientHttpResponse extends AbstractClientHttpResponse {
35  
36  	private final HttpURLConnection connection;
37  
38  	private HttpHeaders headers;
39  
40  
41  	SimpleClientHttpResponse(HttpURLConnection connection) {
42  		this.connection = connection;
43  	}
44  
45  
46  	@Override
47  	public int getRawStatusCode() throws IOException {
48  		return this.connection.getResponseCode();
49  	}
50  
51  	@Override
52  	public String getStatusText() throws IOException {
53  		return this.connection.getResponseMessage();
54  	}
55  
56  	@Override
57  	public HttpHeaders getHeaders() {
58  		if (this.headers == null) {
59  			this.headers = new HttpHeaders();
60  			// Header field 0 is the status line for most HttpURLConnections, but not on GAE
61  			String name = this.connection.getHeaderFieldKey(0);
62  			if (StringUtils.hasLength(name)) {
63  				this.headers.add(name, this.connection.getHeaderField(0));
64  			}
65  			int i = 1;
66  			while (true) {
67  				name = this.connection.getHeaderFieldKey(i);
68  				if (!StringUtils.hasLength(name)) {
69  					break;
70  				}
71  				this.headers.add(name, this.connection.getHeaderField(i));
72  				i++;
73  			}
74  		}
75  		return this.headers;
76  	}
77  
78  	@Override
79  	public InputStream getBody() throws IOException {
80  		InputStream errorStream = this.connection.getErrorStream();
81  		return (errorStream != null ? errorStream : this.connection.getInputStream());
82  	}
83  
84  	@Override
85  	public void close() {
86  		this.connection.disconnect();
87  	}
88  
89  }