-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOkHttpUtils.java
More file actions
567 lines (504 loc) · 18.2 KB
/
OkHttpUtils.java
File metadata and controls
567 lines (504 loc) · 18.2 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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
package com.uiot.video.utils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import com.uiot.video.utils.sign.Encrypt_Tea;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* OkHttpUtils 采用OkHttp封装框架短连接请求,http://square.github.io/okhttp与https://github.com/square/okhttp
*
* @author susanyuan
* @date 2016/9/23 17:44
*/
public class OkHttpUtils {
private static final long DEFAULT_MILLISECONDS = 10000;
private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
private static final MediaType MEDIA_TYPE_STREAM = MediaType.parse("application/octet-stream");
private static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
private static final String TAG = "OkHttpUtils";
private static OkHttpUtils mInstance;
private final Handler mDelivery;
private OkHttpClient mOkHttpClient;
private OkHttpUtils() {
mOkHttpClient = new OkHttpClient();
mDelivery = new Handler(Looper.getMainLooper());
}
public static OkHttpUtils getInstance() {
if (mInstance == null) {
synchronized (OkHttpUtils.class) {
if (mInstance == null) {
mInstance = new OkHttpUtils();
}
}
}
return mInstance;
}
/**
* 设置超时,毫秒,请求之前设置
*
* @param readTimeOut 读取超时,如小于等于0,则默认10000毫秒
* @param writeTimeOut 写入超时,如小于等于0,则默认10000毫秒
* @param connTimeOut 连接超时,如小于等于0,则默认10000毫秒
*/
public static void setTimeout(long readTimeOut, long writeTimeOut, long connTimeOut) {
if (readTimeOut > 0 || writeTimeOut > 0 || connTimeOut > 0) {
readTimeOut = readTimeOut > 0 ? readTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
writeTimeOut = writeTimeOut > 0 ? writeTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
connTimeOut = connTimeOut > 0 ? connTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
getInstance()._setTimeout(readTimeOut, writeTimeOut, connTimeOut);
}
}
/**
* 同步的Get请求
*
* @param url URL
* @return Response
* @throws IOException
*/
public static Response getAsyn(String url) throws IOException {
return getInstance()._getAsyn(url);
}
/**
* 同步的Get请求
*
* @param url URL
* @return 字符串
* @throws IOException
*/
public static String getAsString(String url) throws IOException {
return getInstance()._getAsString(url);
}
/**
* 异步的Get请求
*
* @param url URL
* @param callback 回调
* @param isDecrypt 是否需要解密
*/
public static void getAsyn(String url, boolean isDecrypt, Callback callback) {
getInstance()._getAsyn(url, callback, isDecrypt);
}
/**
* 同步的Post请求
*
* @param url URL
* @param params post的参数
* @return Response
* @throws IOException
*/
public static Response post(String url, Param... params) throws IOException {
return getInstance()._post(url, params);
}
/**
* 同步的Post请求
*
* @param url URL
* @param params post的参数
* @return 字符串
* @throws IOException
*/
public static String postAsString(String url, Param... params) throws IOException {
return getInstance()._postAsString(url, params);
}
/**
* 异步的Post请求
*
* @param url URL
* @param callback 异步回调
* @param isDecrypt 是否需要解密
* @param params post的参数, Param...
*/
public static void postAsyn(String url, boolean isDecrypt, Callback callback, Param... params) {
getInstance()._postAsyn(url, callback, isDecrypt, params);
}
/**
* 异步的Post请求
*
* @param url URL
* @param callback 异步回调
* @param isDecrypt 是否需要解密
* @param params post的参数,此是使用Map
*/
public static void postAsyn(String url, boolean isDecrypt, Map<String, String> params, Callback callback) {
getInstance()._postAsyn(url, callback, isDecrypt, params);
}
/**
* 异步的Post请求,采用Post Streaming方式
*
* @param url URL
* @param callback 异步回调
* @param isDecrypt 是否需要解密
* @param strBody post的stream的字符串
*/
public static void postStreamAsyn(String url, boolean isDecrypt, String strBody, Callback callback) {
getInstance()._postAsyn(url, callback, isDecrypt, strBody);
}
//*************对外公布的方法************
/**
* 得到OkHttpClient实例
*
* @return OkHttpClient
*/
public OkHttpClient getOkHttpClient() {
return mOkHttpClient;
}
private void _setTimeout(long readTimeOut, long writeTimeOut, long connTimeOut) {
mOkHttpClient.newBuilder()
.readTimeout(readTimeOut, TimeUnit.MILLISECONDS)
.writeTimeout(writeTimeOut, TimeUnit.MILLISECONDS)
.connectTimeout(connTimeOut, TimeUnit.MILLISECONDS)
.build();
}
/**
* 同步的Get请求
*
* @param url URL
* @return Response
*/
private Response _getAsyn(String url) throws IOException {
final Request request = new Request.Builder()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
Response execute = call.execute();
return execute;
}
/**
* 同步的Get请求
*
* @param url URL
* @return 字符串
*/
private String _getAsString(String url) throws IOException {
Response execute = _getAsyn(url);
return execute.body().string();
}
/**
* 异步的get请求
*
* @param url URL
* @param callback Callback
*/
private void _getAsyn(String url, Callback callback, boolean isDecrypt) {
final Request request = new Request.Builder()
.url(url)
.build();
deliveryResult(callback, request, isDecrypt);
}
/**
* 同步的Post请求
*
* @param url URL
* @param params post的参数
* @return
*/
private Response _post(String url, Param... params) throws IOException {
Request request = buildPostRequest(url, params);
Response response = mOkHttpClient.newCall(request).execute();
return response;
}
/**
* 同步的Post请求
*
* @param url URL
* @param params post的参数
* @return 字符串
*/
private String _postAsString(String url, Param... params) throws IOException {
Response response = _post(url, params);
return response.body().string();
}
/**
* 异步的post请求
*
* @param url URL
* @param callback Callback
* @param params Param...
*/
private void _postAsyn(String url, Callback callback, boolean isDecrypt, Param... params) {
Request request = buildPostRequest(url, params);
deliveryResult(callback, request, isDecrypt);
}
/**
* 异步的post请求
*
* @param url URL
* @param callback Callback
* @param params Map
*/
private void _postAsyn(String url, Callback callback, boolean isDecrypt, Map<String, String> params) {
Param[] paramsArr = map2Params(params);
Request request = buildPostRequest(url, paramsArr);
deliveryResult(callback, request, isDecrypt);
}
/**
* 异步的post请求
*
* @param url URL
* @param callback Callback
* @param isDecrypt 是否需要解密
* @param strBody post的stream的字符串
*/
private void _postAsyn(String url, Callback callback, boolean isDecrypt, String strBody) {
Request request = buildPostRequest(url, isDecrypt, strBody);
deliveryResult(callback, request, isDecrypt);
}
/**
* 异步下载文件,注意,URL为文件地址,下载后回调的对象为File
*
* @param url 下载文件地址
* @param destFileDir 本地文件存储的文件夹
* @param destFileName 文件名
* @param callback Callback
*/
private void _downloadAsyn(final String url, final String destFileDir, final String destFileName, final Callback callback) {
final Request request = new Request.Builder()
.url(url)
.build();
final Callback finalCallback = callback;
final Call call = mOkHttpClient.newCall(request);
call.enqueue(new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
sendFailResultCallback(call, e, finalCallback);
}
@Override
public void onResponse(Call call, Response response) {
try {
File file = saveFile(response, destFileDir, destFileName);
//如果下载文件成功,第一个参数为文件
sendSuccessResultCallback(file, response, callback);
} catch (IOException e) {
sendFailResultCallback(call, e, finalCallback);
e.printStackTrace();
}
}
});
}
/**
* 异步下载图片,注意,URL为图片地址,下载后回调的对象为Bitmap
*
* @param url
* @param callback
*/
private void _downloadImageAsyn(final String url, final Callback callback) {
final Request request = new Request.Builder()
.url(url)
.build();
final Callback finalCallback = callback;
final Call call = mOkHttpClient.newCall(request);
call.enqueue(new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
sendFailResultCallback(call, e, finalCallback);
}
@Override
public void onResponse(Call call, Response response) {
Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());
//如果下载文件成功,第一个参数为文件
sendSuccessResultCallback(bitmap, response, callback);
}
});
}
/**
* 异步下载文件,注意:URL为文件地址,下载后回调的对象为File
*
* @param url 下载文件地址
* @param destFileDir 本地文件存储的文件夹
* @param destFileName 文件名
* @param callback Callback
*/
public static void downloadAsyn(String url, String destFileDir, String destFileName, Callback callback) {
getInstance()._downloadAsyn(url, destFileDir, destFileName, callback);
}
/**
* 异步下载图片,注意:URL为图片地址,下载后回调的对象为Bitmap
*
* @param url
* @param callback
*/
public static void downloadImageAsyn(String url, Callback callback) {
getInstance()._downloadImageAsyn(url, callback);
}
public File saveFile(Response response, String destFileDir, String destFileName) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try {
is = response.body().byteStream();
File dir = new File(destFileDir);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, destFileName);
fos = new FileOutputStream(file);
// final long total = response.body().contentLength();
// long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
// sum += len;
// final long finalSum = sum;
// mDelivery.post(new Runnable() {
// @Override
// public void run() {
// callback.inProgress(finalSum * 1.0f / total, total);
// }
// });
}
fos.flush();
return file;
} finally {
try {
if (is != null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fos != null) fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Request buildPostRequest(String url, Param[] params) {
if (params == null) {
params = new Param[0];
}
FormBody.Builder builder = new FormBody.Builder();
for (Param param : params) {
builder.add(param.key, param.value);
}
RequestBody requestBody = builder.build();
return new Request.Builder()
.url(url)
.post(requestBody)
.build();
}
private Request buildPostRequest(String url, boolean isDecrypt, String strBody) {
//json
// MediaType JSON =MediaType.parse("application/json; charset=utf-8");
// RequestBody requestBody = RequestBody.create(JSON,json);
//文件
// File file = new File("README.md");
// RequestBody.create(MEDIA_TYPE_STREAM, file)
final byte[] data = strBody.toString().getBytes();
if (isDecrypt) {
/**********这里是你们自己进行加密的方***********/
}
RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, data);
return new Request.Builder()
.url(url)
.post(requestBody)
.build();
}
private void deliveryResult(Callback callback, Request request, final boolean isDecrypt) {
if (callback == null)
callback = Callback.CALLBACK_DEFAULT;
final Callback finalCallback = callback;
mOkHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
@Override
public void onFailure(Call call, IOException e) {
sendFailResultCallback(call, e, finalCallback);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
String string;
if (isDecrypt) {
/*******************这里是你们自己解密方法*********************/
/**********************************************************/
string = response.body().string();
} else {
string = response.body().string();
// Object o = finalCallback.parseNetworkResponse(response);
}
sendSuccessResultCallback(string, response, finalCallback);
} catch (Exception e) {
sendFailResultCallback(call, e, finalCallback);
}
}
});
}
public void sendFailResultCallback(final Call call, final Exception e, final Callback callback) {
if (callback == null) return;
mDelivery.post(new Runnable() {
@Override
public void run() {
callback.onError(call, e);
}
});
}
public void sendSuccessResultCallback(final Object o, final Response response, final Callback callback) {
if (callback == null) return;
mDelivery.post(new Runnable() {
@Override
public void run() {
callback.onResponse(o, response);
}
});
}
private Param[] map2Params(Map<String, String> params) {
if (params == null) return new Param[0];
int size = params.size();
Param[] res = new Param[size];
Set<Map.Entry<String, String>> entries = params.entrySet();
int i = 0;
for (Map.Entry<String, String> entry : entries) {
res[i++] = new Param(entry.getKey(), entry.getValue());
}
return res;
}
public static class Param {
String key;
String value;
public Param() {
}
public Param(String key, String value) {
this.key = key;
this.value = value;
}
}
public abstract static class Callback<T> {
/**
* UI Thread
*
* @param progress
*/
// public void inProgress(float progress) {
//
// }
public static Callback CALLBACK_DEFAULT = new Callback() {
// @Override
// public Object parseNetworkResponse(Response response) throws Exception {
// return null;
// }
@Override
public void onError(Call call, Exception e) {
}
@Override
public void onResponse(Object object, Response response) {
}
};
/**
* Thread Pool Thread
*/
// public abstract T parseNetworkResponse(Response response) throws Exception;
public abstract void onError(Call call, Exception e);
public abstract void onResponse(Object object, Response response);
}
}