View Javadoc
1   package com.foxinmy.weixin4j.http.support.okhttp;
2   
3   import java.io.IOException;
4   import java.net.MalformedURLException;
5   import java.util.List;
6   import java.util.Map.Entry;
7   
8   import okio.BufferedSink;
9   import okio.Okio;
10  import okio.Source;
11  
12  import com.foxinmy.weixin4j.http.AbstractHttpClient;
13  import com.foxinmy.weixin4j.http.HttpClientException;
14  import com.foxinmy.weixin4j.http.HttpHeaders;
15  import com.foxinmy.weixin4j.http.HttpMethod;
16  import com.foxinmy.weixin4j.http.HttpRequest;
17  import com.foxinmy.weixin4j.http.HttpResponse;
18  import com.foxinmy.weixin4j.http.entity.HttpEntity;
19  import com.foxinmy.weixin4j.util.StringUtil;
20  import com.squareup.okhttp.MediaType;
21  import com.squareup.okhttp.OkHttpClient;
22  import com.squareup.okhttp.Request;
23  import com.squareup.okhttp.RequestBody;
24  import com.squareup.okhttp.Response;
25  import com.squareup.okhttp.internal.Util;
26  
27  /**
28   * OkHttp2
29   * 
30   * @className OkHttpClient2
31   * @author jinyu(foxinmy@gmail.com)
32   * @date 2016年7月25日
33   * @since JDK 1.6
34   */
35  public class OkHttpClient2 extends AbstractHttpClient {
36  	private final OkHttpClient okClient;
37  
38  	public OkHttpClient2(OkHttpClient okClient) {
39  		this.okClient = okClient;
40  	}
41  
42  	@Override
43  	public HttpResponse execute(HttpRequest request) throws HttpClientException {
44  		HttpResponse response = null;
45  		try {
46  			Request okRequest = createRequest(request);
47  			Response okResponse = okClient.newCall(okRequest).execute();
48  			response = new OkHttpResponse2(okResponse, okResponse.body()
49  					.bytes());
50  			handleResponse(response);
51  		} catch (IOException e) {
52  			throw new HttpClientException("I/O error on "
53  					+ request.getMethod().name() + " request for \""
54  					+ request.getURI().toString(), e);
55  		} finally {
56  			if (response != null) {
57  				response.close();
58  			}
59  		}
60  		return response;
61  	}
62  
63  	/**
64  	 * create OkRequest
65  	 */
66  	protected Request createRequest(HttpRequest request)
67  			throws HttpClientException {
68  		Request.Builder requestBuilder = createBuilder(request);
69  		resolveHeaders(request.getHeaders(), requestBuilder);
70  		resolveContent(request.getEntity(), request.getMethod(), requestBuilder);
71  		return requestBuilder.build();
72  	}
73  
74  	/**
75  	 * create Request.Builder
76  	 * 
77  	 * @throws HttpClientException
78  	 */
79  	protected Request.Builder createBuilder(HttpRequest request)
80  			throws HttpClientException {
81  		Request.Builder requestBuilder = new Request.Builder();
82  		try {
83  			requestBuilder.url(request.getURI().toURL());
84  		} catch (MalformedURLException e) {
85  			throw new HttpClientException("format URI error", e);
86  		}
87  		return requestBuilder;
88  	}
89  
90  	/**
91  	 * resolve Request.Headers
92  	 * */
93  	protected void resolveHeaders(
94  			com.foxinmy.weixin4j.http.HttpHeaders headers,
95  			Request.Builder requestBuilder) {
96  		if (headers == null) {
97  			headers = new HttpHeaders();
98  		}
99  		// Add default accept headers
100 		if (!headers.containsKey(HttpHeaders.ACCEPT)) {
101 			headers.set(HttpHeaders.ACCEPT, "*/*");
102 		}
103 		// Add default user agent
104 		if (!headers.containsKey(HttpHeaders.USER_AGENT)) {
105 			headers.set(HttpHeaders.USER_AGENT, "square/okhttp2");
106 		}
107 		for (Entry<String, List<String>> header : headers.entrySet()) {
108 			if (HttpHeaders.COOKIE.equalsIgnoreCase(header.getKey())) {
109 				requestBuilder.header(header.getKey(),
110 						StringUtil.join(header.getValue(), ';'));
111 			} else {
112 				for (String headerValue : header.getValue()) {
113 					requestBuilder.header(header.getKey(),
114 							headerValue != null ? headerValue : "");
115 				}
116 			}
117 		}
118 	}
119 
120 	/**
121 	 * resolve Request.Content
122 	 */
123 	protected void resolveContent(final HttpEntity entity, HttpMethod method,
124 			Request.Builder requestBuilder) throws HttpClientException {
125 		RequestBody body = null;
126 		if (entity != null) {
127 			body = new RequestBody() {
128 
129 				@Override
130 				public long contentLength() throws IOException {
131 					return entity.getContentLength();
132 				}
133 
134 				@Override
135 				public void writeTo(BufferedSink sink) throws IOException {
136 					Source source = null;
137 					try {
138 						source = Okio.source(entity.getContent());
139 						sink.writeAll(source);
140 					} finally {
141 						Util.closeQuietly(source);
142 					}
143 				}
144 
145 				@Override
146 				public MediaType contentType() {
147 					return MediaType.parse(entity.getContentType().toString());
148 				}
149 			};
150 		}
151 		requestBuilder.method(method.name(), body);
152 	}
153 }