OKHttp3学习之六:文件下载(简单方式)

需求:下载网络文件到手机SD卡上

在app模块的build.gradle配置

1
compile 'com.squareup.okhttp3:okhttp:3.4.2'

实现源码

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
private static final String fileUrl = "http://dldir1.qq.com/weixin/android/weixin6331android940.apk";
private static final String fileName = "weixin6331android940.apk";

public void downloadFile(View view) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(fileUrl).build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "请求失败: " + e.getLocalizedMessage());
}

@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
ResponseBody body = response.body();
if (body != null) {
writeFile(body);
}
}
}
});
}

//主线程更新UI进度
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
int progress = msg.arg1;
mProgressBar.setProgress(progress);
break;

default:
break;
}
}
};

private void writeFile(ResponseBody body) {
InputStream is = null; //网络输入流
FileOutputStream fos = null; //文件输出流

is = body.byteStream();

String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + fileName;
File file = new File(filePath);
try {
fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
long totalSize = body.contentLength(); //文件总大小
long sum = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / totalSize * 100);
Message msg = handler.obtainMessage();
msg.what = 1;
msg.arg1 = progress;
handler.sendMessage(msg);
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :