HttpInterface.java
9.34 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package com.huaheng.mes.https;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.huaheng.mes.MESApplication;
import com.huaheng.mes.bean.Constant;
import com.huaheng.mes.https.convert.ResponseConverterFactory;
import com.huaheng.mes.util.MESUtils;
import com.huaheng.mes.util.MESlog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
public class HttpInterface {
public final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static HttpInterface insstance = null;
private Retrofit retrofit;
private Map<String, Object> paramMap;
private OkHttpClient.Builder clientBuilder;
private HttpService httpService;
public static HttpInterface getInsstance() {
MESlog.d("HttpInterface insstance:" + insstance);
if (insstance == null) {
insstance = new HttpInterface();
}
return insstance;
}
public HttpInterface() {
MESlog.d("HttpInterface");
TrustManager[] trustManager = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws
CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws
CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null; // 返回null
}
}
};
clientBuilder = new OkHttpClient.Builder();
try {
clientBuilder
.connectTimeout(HttpConstant.CONNECT_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(HttpConstant.WRITE_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(HttpConstant.READ_TIMEOUT, TimeUnit.SECONDS)
.sslSocketFactory(getSSLSocketFactory())
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
clientBuilder.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
// 获取 Cookie
Response resp = chain.proceed(chain.request());
List<String> cookies = resp.headers("Set-Cookie");
String cookieStr = "";
if (cookies != null && cookies.size() > 0) {
for (int i = 0; i < cookies.size(); i++) {
cookieStr += cookies.get(i);
}
MESApplication.setOkhttpCookie(cookieStr);
}
return resp;
}
});
clientBuilder.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
// 设置 Cookie
String cookieStr = MESApplication.getOkhttpCookie();
if (!TextUtils.isEmpty(cookieStr)) {
return chain.proceed(chain.request().newBuilder().header("Cookie", cookieStr).build());
}
return chain.proceed(chain.request());
}
});
clientBuilder.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("Content-Type", "application/json")
.addHeader("token",MESApplication.getToken())
.addHeader("accept", "application/json").build();
return chain.proceed(request);
}
});
} catch (Exception e) {
e.printStackTrace();
}
String url = MESUtils.getData(Constant.NETWORK);
if(url != null) {
retrofit = new Retrofit.Builder()
.client(clientBuilder.build())
.addConverterFactory(ResponseConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(url)
.build();
} else {
retrofit = new Retrofit.Builder()
.client(clientBuilder.build())
.addConverterFactory(ResponseConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(HttpConstant.URL)
.build();
}
paramMap = new HashMap<>();
MESlog.d("initService");
initService(retrofit);
}
public void reset() {
insstance = null;
}
private static SSLSocketFactory getSSLSocketFactory() throws Exception {
//创建一个不验证证书链的证书信任管理器。
final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(
X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(
X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
return sslContext.getSocketFactory();
}
public void setBaseUrl(String url) {
retrofit = new Retrofit.Builder()
.client(clientBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(url)
.build();
initService(retrofit);
}
private void initService(Retrofit retrofit) {
httpService = retrofit.create(HttpService.class);
}
public String getBaseUrl() {
return retrofit.baseUrl().toString();
}
public void login(Subscriber<ArrayList<String>> subscriber, String userName, String password) {
JSONObject json = new JSONObject();
try {
json.put("code", userName);
json.put("password", password);
} catch (JSONException e) {
e.printStackTrace();
}
MESlog.d("login :" + json.toString());
MESApplication.setOkhttpCookie(null);
RequestBody formBody = RequestBody.create(JSON, json.toString());
Observable observable = httpService.login(formBody)
.map(new ApiResponseFunc<String>());
toSubscribe(observable, subscriber);
}
/**
* 用来统一处理Http的resultCode,并将HttpResult的Data部分剥离出来返回给subscriber
*
* @param <T> Subscriber真正需要的数据类型,也就是Data部分的数据类型
*/
private class ApiResponseFunc<T> implements Func1<ApiResponse<T>, T> {
@Override
public T call(ApiResponse<T> apiResponse) {
if (!apiResponse.getCode().equals("200")) {
throw new ApiException(apiResponse.getMsg());
}
if (apiResponse.getData() != null) {
return apiResponse.getData();
} else if (apiResponse.getSession() != null) {
return apiResponse.getSession();
}
return null;
}
}
private void toSubscribe(Observable observable, Subscriber subscriber) {
observable
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
}