View Javadoc
1   package com.foxinmy.weixin4j.http.support.apache4;
2   
3   import java.io.IOException;
4   
5   import org.apache.http.Header;
6   import org.apache.http.ProtocolVersion;
7   import org.apache.http.StatusLine;
8   import org.apache.http.client.methods.CloseableHttpResponse;
9   import org.apache.http.util.EntityUtils;
10  
11  import com.foxinmy.weixin4j.http.AbstractHttpResponse;
12  import com.foxinmy.weixin4j.http.HttpHeaders;
13  import com.foxinmy.weixin4j.http.HttpStatus;
14  import com.foxinmy.weixin4j.http.HttpVersion;
15  
16  /**
17   * HttpComponent4 Response:Requires Apache HttpComponents 4.3 or higher
18   * 
19   * @className HttpComponent4_2Response
20   * @author jinyu(foxinmy@gmail.com)
21   * @date 2015年8月18日
22   * @since JDK 1.6
23   * @see
24   */
25  public class HttpComponent4_2Response extends AbstractHttpResponse {
26  
27  	private final CloseableHttpResponse httpResponse;
28  
29  	private HttpHeaders headers;
30  	private HttpVersion protocol;
31  	private HttpStatus status;
32  
33  	public HttpComponent4_2Response(CloseableHttpResponse httpResponse,
34  			byte[] content) {
35  		super(content);
36  		this.httpResponse = httpResponse;
37  	}
38  
39  	@Override
40  	public HttpHeaders getHeaders() {
41  		if (headers == null) {
42  			headers = new HttpHeaders();
43  			Header[] headers = httpResponse.getAllHeaders();
44  			for (Header header : headers) {
45  				this.headers.add(header.getName(), header.getValue());
46  			}
47  		}
48  		return headers;
49  	}
50  
51  	@Override
52  	public HttpVersion getProtocol() {
53  		if (protocol == null) {
54  			ProtocolVersion version = httpResponse.getProtocolVersion();
55  			Header connection = httpResponse.getFirstHeader("Connection");
56  			protocol = new HttpVersion(version.getProtocol(),
57  					version.getMajor(), version.getMinor(), connection != null
58  							&& KEEP_ALIVE.equalsIgnoreCase(connection
59  									.getValue()));
60  		}
61  		return protocol;
62  	}
63  
64  	@Override
65  	public HttpStatus getStatus() {
66  		if (status == null) {
67  			StatusLine statusLine = httpResponse.getStatusLine();
68  			status = new HttpStatus(statusLine.getStatusCode(),
69  					statusLine.getReasonPhrase());
70  		}
71  		return status;
72  	}
73  
74  	@Override
75  	public void close() {
76  		try {
77  			EntityUtils.consume(httpResponse.getEntity());
78  			httpResponse.close();
79  		} catch (IOException ex) {
80  			;
81  		}
82  	}
83  }