View Javadoc
1   package com.foxinmy.weixin4j.http.support.okhttp;
2   
3   import okhttp3.Protocol;
4   
5   import com.foxinmy.weixin4j.http.AbstractHttpResponse;
6   import com.foxinmy.weixin4j.http.HttpHeaders;
7   import com.foxinmy.weixin4j.http.HttpStatus;
8   import com.foxinmy.weixin4j.http.HttpVersion;
9   
10  /**
11   * OkHttp Response:Requires OkHttp 3.x or higher
12   * 
13   * @className OkHttpResponse3
14   * @author jinyu(foxinmy@gmail.com)
15   * @date 2016年7月25日
16   * @since JDK 1.6
17   */
18  public class OkHttpResponse3 extends AbstractHttpResponse {
19  	private final okhttp3.Response response;
20  	private HttpHeaders headers;
21  	private HttpVersion protocol;
22  	private HttpStatus status;
23  
24  	public OkHttpResponse3(okhttp3.Response response, byte[] content) {
25  		super(content);
26  		this.response = response;
27  	}
28  
29  	@Override
30  	public HttpHeaders getHeaders() {
31  		if (this.headers == null) {
32  			this.headers = new HttpHeaders();
33  			okhttp3.Headers headers = this.response.headers();
34  			for (int i = 0; i < headers.size(); i++) {
35  				this.headers.add(headers.name(i), headers.value(i));
36  			}
37  		}
38  		return this.headers;
39  	}
40  
41  	@Override
42  	public HttpVersion getProtocol() {
43  		if (protocol == null) {
44  			String protocol = this.response.protocol().toString().split("/")[0];
45  			boolean keepAlive = KEEP_ALIVE.equalsIgnoreCase(this.response
46  					.header("Connection"));
47  			if (this.response.protocol() == Protocol.HTTP_1_0) {
48  				return new HttpVersion(protocol, 1, 0, keepAlive);
49  			} else if (this.response.protocol() == Protocol.HTTP_1_1) {
50  				return new HttpVersion(protocol, 1, 1, keepAlive);
51  			} else if (this.response.protocol() == Protocol.HTTP_2) {
52  				return new HttpVersion(protocol, 2, 0, keepAlive);
53  			} else if (this.response.protocol() == Protocol.SPDY_3) {
54  				return new HttpVersion(protocol, 3, 0, keepAlive);
55  			} else {
56  				this.protocol = new HttpVersion(protocol, keepAlive);
57  			}
58  		}
59  		return protocol;
60  	}
61  
62  	@Override
63  	public HttpStatus getStatus() {
64  		if (status == null) {
65  			status = new HttpStatus(this.response.code(),
66  					this.response.message());
67  		}
68  		return status;
69  	}
70  
71  	@Override
72  	public void close() {
73  		response.close();
74  	}
75  }