OKHttp3学习之六:文件下载(简单方式)
需求:下载网络文件到手机SD卡上
在app模块的build.gradle配置
compile 'com.squareup.okhttp3:okhttp:3.4.2'
实现源码
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();
}
}
}
}
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/02/25/okhttp3-learning-6-file-download-simple-method/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
THE END
0
二维码
打赏
海报
OKHttp3学习之六:文件下载(简单方式)
需求:下载网络文件到手机SD卡上
在app模块的build.gradle配置
compile 'com.squareup.okhttp3:okhttp:3.4.2'
实现源码
private static final Stri……
文章目录
关闭
共有 0 条评论