1 package com.foxinmy.weixin4j.http.support.okhttp;
2
3 import java.net.CookieHandler;
4 import java.util.concurrent.TimeUnit;
5
6 import com.foxinmy.weixin4j.http.HttpClient;
7 import com.foxinmy.weixin4j.http.HttpParams;
8 import com.foxinmy.weixin4j.http.factory.HttpClientFactory;
9 import com.squareup.okhttp.Cache;
10 import com.squareup.okhttp.ConnectionPool;
11 import com.squareup.okhttp.Dispatcher;
12 import com.squareup.okhttp.Dns;
13 import com.squareup.okhttp.OkHttpClient;
14
15
16
17
18
19
20
21
22
23 public class OkHttpClient2Factory extends HttpClientFactory {
24 private final OkHttpClient okClient;
25
26 public OkHttpClient2Factory() {
27 okClient = new OkHttpClient();
28 okClient.setHostnameVerifier(HttpClientFactory.AllowHostnameVerifier.GLOBAL);
29 okClient.setSslSocketFactory(HttpClientFactory.allowSSLContext()
30 .getSocketFactory());
31 }
32
33 public OkHttpClient2Factory(OkHttpClient okClient) {
34 this.okClient = okClient;
35 }
36
37 private void resolveHttpParams(HttpParams params) {
38 if (params != null) {
39 okClient.setConnectTimeout(params.getConnectTimeout(),
40 TimeUnit.MILLISECONDS);
41 okClient.setReadTimeout(params.getReadTimeout(),
42 TimeUnit.MILLISECONDS);
43 if (params.getProxy() != null) {
44 okClient.setProxy(params.getProxy());
45 }
46 if (params.getSSLContext() != null) {
47 okClient.setSslSocketFactory(params.getSSLContext()
48 .getSocketFactory());
49 }
50 if (params.getHostnameVerifier() != null) {
51 okClient.setHostnameVerifier(params.getHostnameVerifier());
52 }
53 okClient.getDispatcher().setMaxRequests(params.getMaxConnections());
54 okClient.getDispatcher().setMaxRequestsPerHost(params.getMaxConnectionsPerHost());
55 }
56 }
57
58 public OkHttpClient2Factory setWriteTimeout(int writeTimeout) {
59 okClient.setWriteTimeout(writeTimeout, TimeUnit.MILLISECONDS);
60 return this;
61 }
62
63 public OkHttpClient2Factory setCache(Cache cache) {
64 okClient.setCache(cache);
65 return this;
66 }
67
68 public OkHttpClient2Factory setConnectionPool(ConnectionPool connectionPool) {
69 okClient.setConnectionPool(connectionPool);
70 return this;
71 }
72
73 public OkHttpClient2Factory setCookieHandler(CookieHandler cookieHandler) {
74 okClient.setCookieHandler(cookieHandler);
75 return this;
76 }
77
78 public OkHttpClient2Factory setDispatcher(Dispatcher dispatcher) {
79 okClient.setDispatcher(dispatcher);
80 return this;
81 }
82
83 public OkHttpClient2Factory setDns(Dns dns) {
84 okClient.setDns(dns);
85 return this;
86 }
87
88 @Override
89 public HttpClient newInstance(HttpParams params) {
90 resolveHttpParams(params);
91 return new OkHttpClient2(okClient);
92 }
93 }