View Javadoc
1   package com.foxinmy.weixin4j.http;
2   
3   import java.io.IOException;
4   import java.net.HttpURLConnection;
5   import java.util.List;
6   import java.util.Map;
7   import java.util.Map.Entry;
8   
9   /**
10   * Simple Response
11   * 
12   * @className SimpleHttpResponse
13   * @author jinyu(foxinmy@gmail.com)
14   * @date 2015年8月14日
15   * @since JDK 1.6
16   * @see
17   */
18  public class SimpleHttpResponse extends AbstractHttpResponse {
19  
20  	private final HttpURLConnection connection;
21  
22  	private HttpHeaders headers;
23  	private HttpVersion protocol;
24  	private HttpStatus status;
25  
26  	public SimpleHttpResponse(HttpURLConnection connection, byte[] content) {
27  		super(content);
28  		this.connection = connection;
29  	}
30  
31  	@Override
32  	public HttpVersion getProtocol() {
33  		String version = connection.getHeaderField(null);
34  		if (version == null) {
35  			return null;
36  		}
37  		if (protocol == null) {
38  			if (version.contains(HttpVersion.HTTP_1_0_STRING)) {
39  				protocol = HttpVersion.HTTP_1_0;
40  			} else if (version.contains(HttpVersion.HTTP_1_1_STRING)) {
41  				protocol = HttpVersion.HTTP_1_1;
42  			} else {
43  				String connect = connection.getHeaderField("Connection");
44  				protocol = new HttpVersion(version,
45  						KEEP_ALIVE.equalsIgnoreCase(connect));
46  			}
47  		}
48  		return protocol;
49  	}
50  
51  	@Override
52  	public HttpHeaders getHeaders() {
53  		if (headers == null) {
54  			headers = new HttpHeaders();
55  			Map<String, List<String>> headerFields = connection
56  					.getHeaderFields();
57  			for (Entry<String, List<String>> headerEntry : headerFields
58  					.entrySet()) {
59  				headers.put(headerEntry.getKey(), headerEntry.getValue());
60  			}
61  		}
62  		return headers;
63  	}
64  
65  	@Override
66  	public HttpStatus getStatus() {
67  		if (status == null) {
68  			try {
69  				status = new HttpStatus(connection.getResponseCode(),
70  						connection.getResponseMessage());
71  			} catch (IOException e) {
72  				throw new RuntimeException("I/O Error on getStatus", e);
73  			}
74  		}
75  		return status;
76  	}
77  
78  	@Override
79  	public void close() {
80  		connection.disconnect();
81  	}
82  }