forked from liujingxing/rxhttp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpSender.java
More file actions
90 lines (73 loc) · 2.49 KB
/
HttpSender.java
File metadata and controls
90 lines (73 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package rxhttp;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import rxhttp.wrapper.ssl.HttpsUtils;
import rxhttp.wrapper.ssl.HttpsUtils.SSLParams;
import rxhttp.wrapper.utils.LogUtil;
/**
* User: ljx
* Date: 2017/12/2
* Time: 11:13
*/
public final class HttpSender {
private static OkHttpClient mOkHttpClient;
public static void init(OkHttpClient okHttpClient, boolean debug) {
setDebug(debug);
init(okHttpClient);
}
public static void init(OkHttpClient okHttpClient) {
if (mOkHttpClient != null)
throw new IllegalArgumentException("OkHttpClient can only be initialized once");
mOkHttpClient = okHttpClient;
}
public static boolean isInit() {
return mOkHttpClient != null;
}
public static OkHttpClient getOkHttpClient() {
if (mOkHttpClient == null)
mOkHttpClient = getDefaultOkHttpClient();
return mOkHttpClient;
}
public static OkHttpClient.Builder newOkClientBuilder() {
return getOkHttpClient().newBuilder();
}
public static void setDebug(boolean debug) {
LogUtil.setDebug(debug);
}
//Default OkHttpClient object in RxHttp
private static OkHttpClient getDefaultOkHttpClient() {
SSLParams sslParams = HttpsUtils.getSslSocketFactory();
return new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
.hostnameVerifier((hostname, session) -> true)
.build();
}
//Cancel all requests.
static void cancelAll() {
final OkHttpClient okHttpClient = mOkHttpClient;
if (okHttpClient == null) return;
okHttpClient.dispatcher().cancelAll();
}
//Cancel all requests by tag
static void cancelTag(Object tag) {
if (tag == null) return;
final OkHttpClient okHttpClient = mOkHttpClient;
if (okHttpClient == null) return;
Dispatcher dispatcher = okHttpClient.dispatcher();
for (Call call : dispatcher.queuedCalls()) {
if (tag.equals(call.request().tag())) {
call.cancel();
}
}
for (Call call : dispatcher.runningCalls()) {
if (tag.equals(call.request().tag())) {
call.cancel();
}
}
}
}