View Javadoc
1   package com.foxinmy.weixin4j.http.support.netty;
2   
3   import io.netty.channel.ChannelHandlerContext;
4   import io.netty.handler.codec.http.FullHttpResponse;
5   import io.netty.handler.codec.http.HttpResponseStatus;
6   
7   import java.util.Map;
8   
9   import com.foxinmy.weixin4j.http.AbstractHttpResponse;
10  import com.foxinmy.weixin4j.http.HttpHeaders;
11  import com.foxinmy.weixin4j.http.HttpStatus;
12  import com.foxinmy.weixin4j.http.HttpVersion;
13  
14  /**
15   * Netty Response::Requires Netty 4.x or higher
16   *
17   * @className Netty4HttpResponse
18   * @author jinyu(foxinmy@gmail.com)
19   * @date 2015年8月30日
20   * @since JDK 1.6
21   * @see
22   */
23  public class Netty4HttpResponse extends AbstractHttpResponse {
24  
25  	private final ChannelHandlerContext context;
26  	private final FullHttpResponse response;
27  
28  	private HttpVersion protocol;
29  	private HttpStatus status;
30  	private HttpHeaders headers;
31  
32  	public Netty4HttpResponse(ChannelHandlerContext context,
33  			FullHttpResponse response, byte[] content) {
34  		super(content);
35  		this.context = context;
36  		this.response = response;
37  		this.response.retain();
38  	}
39  
40  	@Override
41  	public HttpHeaders getHeaders() {
42  		if (this.headers == null) {
43  			this.headers = new HttpHeaders();
44  			for (Map.Entry<String, String> entry : this.response.headers()) {
45  				headers.add(entry.getKey(), entry.getValue());
46  			}
47  		}
48  		return this.headers;
49  	}
50  
51  	@Override
52  	public HttpVersion getProtocol() {
53  		if (protocol == null) {
54  			io.netty.handler.codec.http.HttpVersion version = response
55  					.getProtocolVersion();
56  			this.protocol = new HttpVersion(version.protocolName(),
57  					version.majorVersion(), version.majorVersion(),
58  					version.isKeepAliveDefault());
59  		}
60  		return protocol;
61  	}
62  
63  	@Override
64  	public HttpStatus getStatus() {
65  		if (status == null) {
66  			HttpResponseStatus status = response.getStatus();
67  			this.status = new HttpStatus(status.code(), status.reasonPhrase());
68  		}
69  		return status;
70  	}
71  
72  	@Override
73  	public void close() {
74  		this.response.release();
75  		this.context.close();
76  	}
77  }