-
Notifications
You must be signed in to change notification settings - Fork 0
/
abuHttp.java
566 lines (480 loc) · 16.6 KB
/
abuHttp.java
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
package com.abu.healthandroidpad.util;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.ImageView;
import com.abu.healthandroidpad.util.disklrucache.DiskLruCache;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author 阿布
* @date 2016-4-13 下午2:12:06
* 子线程应该在空闲时对cup资源让步
* CacheManager.getDiskLruCache(activity.getApplicationContext(), "bitmap").flush();//不应该常用,应该在activity.onPause()里用
* 图片加载逻辑步骤: 运存里有资源否 - 硬盘有资源否 ; 加载到硬盘 - 显示到UI - 保存到运存
*/
public class abuHttp {
private static ExecutorService mExecutorService;
//服务器响应的回调接口
public static interface OnResponseListener{
public void onResponse(String responseStr);
public void onError(IOException e, int responseCode);
}
private static ExecutorService getThreadPool(){
if(mExecutorService == null)
mExecutorService = Executors.newFixedThreadPool(10);//线程池里最多10个线程处理任务,多余的任务会阻塞
return mExecutorService;
}
/**
*@author abu 2016/5/16 21:55
* 返回任务引用的 图片加载 推荐使用此方法 并且建议管理 这些加载的任务
* 此处 运存里有资源否 - 硬盘有资源否 ; 加载到硬盘 - 显示到UI - 保存到运存
*/
public static Runnable LoadImage(final Activity activity, final String strUrl, final ImageView imageView){
Runnable r = new Runnable(){
private boolean tryStop = false;
private boolean tryDestroy = false;
public void tryStop(){
tryStop = true;
}
public void tryStart(){
tryStop = false;
}
public void tryDestroy(){
tryDestroy = true;
}
private void setView(final Bitmap bitmap){
if(!tryStop && !tryDestroy && activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
}
@Override
public void run() {
Bitmap bitmap;
try {
//运存里有资源否
if((bitmap = CacheManager.getBitmapFromLruCache(strUrl)) != null){
setView(bitmap);
return;
}
//硬盘有资源否
String key = CacheManager.str2md5(strUrl);
DiskLruCache.Snapshot snapShot = CacheManager.getDiskLruCache(activity.getApplicationContext(), "bitmap")
.get(key);
if(snapShot != null && (bitmap = BitmapFactory.decodeStream(snapShot.getInputStream(0))) != null){
setView(bitmap);
return;
}
//加载到硬盘
DiskLruCache.Editor editor = CacheManager.getDiskLruCache(activity.getApplicationContext(), "bitmap")
.edit(CacheManager.str2md5(strUrl));
if (editor != null) {
OutputStream outputStream = editor.newOutputStream(0);
if (downloadUrlToStream(strUrl, outputStream)) {
editor.commit();
} else {
editor.abort();
}
CacheManager.getDiskLruCache(activity.getApplicationContext(), "bitmap").flush();//不应该常用,应该在activity.onPause()里用
//显示到UI
snapShot = null;
bitmap = null;
snapShot = CacheManager.getDiskLruCache(activity.getApplicationContext(), "bitmap")
.get(key);
if(snapShot != null && (bitmap = BitmapFactory.decodeStream(snapShot.getInputStream(0))) != null){
setView(bitmap);
//保存到运存
CacheManager.addBitmapToLruCache(strUrl, bitmap);
return;
}
}
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
setView(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
};
getThreadPool().execute(r);
return r;
}
private static boolean downloadUrlToStream(String urlString, OutputStream outputStream) {
HttpURLConnection urlConnection = null;
BufferedOutputStream out = null;
BufferedInputStream in = null;
try {
final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);
out = new BufferedOutputStream(outputStream, 8 * 1024);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
return true;
} catch (final IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (final IOException e) {
e.printStackTrace();
}
}
return false;
}
/**
*@author abu 2016/4/19 1:05
* 简单图片加载
* 不推荐使用
*/
public static class LoadImageThread extends Thread{
private boolean tryStop = false;
private boolean tryDestroy = false;
private Activity activity;
private String strUrl;
private ImageView imageView;
public LoadImageThread(Activity activity, String strUrl, ImageView imageView){
this.activity = activity;
this.strUrl = strUrl;
this.imageView = imageView;
}
public void tryStop(){
tryStop = true;
}
public void tryStart(){
tryStop = false;
}
public void tryDestroy(){
tryDestroy = true;
}
@Override
public void run() {
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = conn.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
if(!tryStop && !tryDestroy && activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*@author abu 2016/4/19 1:05
* 简单单个文件上传
*/
public static class UpLoadThread extends Thread{
private boolean tryStop = false;
private boolean tryDestroy = false;
private Activity activity;
private OnResponseListener onResponseListener;
private String strUrl;
private Map<String, String> params;
private String fileKey ;
private File file;
private String encode = "utf-8";//默认编码
private int readTimeOut = 10 * 1000;
private int connectTimeOut = 10 * 1000;
private String BOUNDARY = UUID.randomUUID().toString();
public UpLoadThread(Activity activity, String strUrl, Map<String, String> params, String fileKey, File file, String encode, OnResponseListener onResponseListener){
this.activity = activity;
this.strUrl = strUrl;
this.params = params;
this.fileKey = fileKey;
this.file = file;
if(encode != null)
this.encode = encode;
this.onResponseListener = onResponseListener;
}
public void tryStop(){
tryStop = true;
}
public void tryStart(){
tryStop = false;
}
public void tryDestroy(){
tryDestroy = true;
}
private void onResponse(final String str){
if(activity == null) return;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if(!tryStop && !tryDestroy)
onResponseListener.onResponse(str);
}
});
}
private void onError(final IOException e, final int responseCode){
if(activity == null) return;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if(!tryStop && !tryDestroy)
onResponseListener.onError(e, responseCode);
}
});
}
@Override
public void run() {
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(readTimeOut);
conn.setConnectTimeout(connectTimeOut);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", encode); // 设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", "multipart/form-data" + ";boundary=" + BOUNDARY);
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb ;
/***
* 以下是用于上传参数
*/
if (params != null && params.size() > 0) {
Iterator<String> it = params.keySet().iterator();
while (it.hasNext()) {
sb = new StringBuffer();
String key = it.next();
String value = params.get(key);
sb.append("--").append(BOUNDARY).append("\r\n");
sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append("\r\n").append("\r\n");
sb.append(value).append("\r\n");
dos.write(sb.toString().getBytes());
}
}
sb = new StringBuffer();
/**
* 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
sb.append("--").append(BOUNDARY).append("\r\n");
sb.append("Content-Disposition:form-data; name=\"" + fileKey
+ "\"; filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:image/pjpeg" + "\r\n"); // 这里配置的Content-type很重要的 ,用于服务器端辨别文件的类型的
sb.append("\r\n");
dos.write( sb.toString().getBytes());
sb = null;
/**上传文件*/
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];//1kb
int len = 0;
int curLen = 0;
while ((len = is.read(bytes)) != -1) {
curLen += len;
dos.write(bytes, 0, len);
System.out.println("::file.length:"+file.length()+"\n::curLen:"+curLen);
}
is.close();
dos.write("\r\n".getBytes());
dos.write(("--" + BOUNDARY + "--" + "\r\n").getBytes());
dos.flush();
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
int responseCode = conn.getResponseCode();
System.out.println("responseCode:"+responseCode);
if (responseCode == 200) {
final InputStream input = conn.getInputStream();
if(!tryStop && !tryDestroy)
onResponse(dealResponseResult(input));
} else {
if(!tryStop && !tryDestroy)
onError(null, responseCode);
}
} catch (MalformedURLException e) {
if(!tryStop && !tryDestroy)
onError(e, 0);
} catch (IOException e) {
if(!tryStop && !tryDestroy)
onError(e, 0);
}
}
}
/**
*@author abu 2016/4/18 22:54
* 简单表单请求
*/
public static class PostThread extends Thread{
private boolean tryStop = false;
private boolean tryDestroy = false;
private OnResponseListener onResponseListener;
private String strUrl;
private Map<String, String> params;
private String encode = "utf-8";//默认编码
private Activity activity;
public PostThread(Activity activity, String strUrl, Map<String, String> params, String encode, OnResponseListener onResponseListener){
this.activity = activity;
this.strUrl = strUrl;
this.params = params;
if(encode != null)
this.encode = encode;
this.onResponseListener = onResponseListener;
}
//jvm对线程的释放不完善,自己控制,run里有循环体控制while(runable),或者简单的控制run后的结果操作
public void tryStop(){
tryStop = true;
}
public void tryStart(){
tryStop = false;
}
public void tryDestroy(){
tryDestroy = true;
}
private void onResponse(final String str){
if(activity == null) return;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if(!tryStop && !tryDestroy)
onResponseListener.onResponse(str);
}
});
}
private void onError(final IOException e, final int responseCode){
if(activity == null) return;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if(!tryStop && !tryDestroy)
onResponseListener.onError(e, responseCode);
}
});
}
@Override
public void run() {
byte[] data = getRequestData(params, encode).toString().getBytes();//获得请求体的二进制
try {
URL url = new URL(strUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setReadTimeout(6000);
httpURLConnection.setConnectTimeout(6000); //设置连接超时时间
httpURLConnection.setDoInput(true); //打开输入流,以便从服务器获取数据
httpURLConnection.setDoOutput(true); //打开输出流,以便向服务器提交数据
httpURLConnection.setRequestMethod("POST"); //设置以Post方式提交数据
httpURLConnection.setUseCaches(false); //不使用缓存
// httpURLConnection.setRequestProperty("Charset", encode); // 设置编码
// httpURLConnection.setRequestProperty("connection", "keep-alive");
// httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data" + ";boundary=" + UUID.randomUUID().toString());//内容类型;边界标识符随机生成(多种数据传输使能)
//设置请求体的类型是文本类型
// //text/xml -> xml数据 application/json -> json对象 application/x-www-form-urlencoded -> 表单数据 multipart/form-data -> 多种数据
// httpURLConnection.setRequestProperty("Content-Type", "application/x-javascript; charset="+ encode);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置请求体的长度
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
//获得输出流,向服务器写入数据
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(data);
int responseCode = httpURLConnection.getResponseCode(); //获得服务器的响应码
if(responseCode == HttpURLConnection.HTTP_OK) {
final InputStream inptStream = httpURLConnection.getInputStream();
if(!tryStop && !tryDestroy)
onResponse(dealResponseResult(inptStream));
} else {
if(!tryStop && !tryDestroy)
onError(null, responseCode);
}
} catch (MalformedURLException e) {
if(!tryStop && !tryDestroy)
onError(e, 0);
} catch (IOException e) {
if(!tryStop && !tryDestroy)
onError(e, 0);
}
}
}
//inputStream2String
public final static String dealResponseResult(InputStream inptStream) {
String resultData = null; //存储处理结果
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
try {
while((len = inptStream.read(data)) != -1) {
byteArrayOutputStream.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
resultData = new String(byteArrayOutputStream.toByteArray());
return resultData;
}
//参数转StringBuilder
public final static StringBuilder getRequestData(Map<String, String> params,String encode) {
StringBuilder sb = new StringBuilder();//非线程安全
try {
for(Map.Entry<String, String> entry : params.entrySet()) {
sb.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&");
}
sb.deleteCharAt(sb.length() - 1); //删除最后的一个"&"
} catch (Exception e) {
e.printStackTrace();
}
return sb;
}
//判断是否有网
public static boolean isNetWorkConnected(Context context) {
boolean bisConnFlag = false;
ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = conManager.getActiveNetworkInfo();
if(network!=null){
bisConnFlag = conManager.getActiveNetworkInfo().isAvailable();
}
// if(!bisConnFlag)
// XUtil.tipDialogNetWork(context, null, null);//没网则进入网络设置页面
return bisConnFlag;
}
}