
Android 浏览器 —— 使用 WebView 实现文件下载
发布日期:2021-05-09 06:09:59
浏览次数:11
分类:博客文章
本文共 1749 字,大约阅读时间需要 5 分钟。
对当前的WebView设置下载监听
mCurrentWebView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(final String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { // TODO 实现下载逻辑 Log.e("onDownloadStart", "url===" + url + "---userAgent=" + userAgent + "---contentDisposition=" + contentDisposition + "---mimetype=" + mimetype + "---contentLength=" + contentLength); }});
下载文件核心代码:
HttpParams params = new BasicHttpParams();HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);HttpConnectionParams.setSoTimeout(params, 5 * 1000);HttpGet httpGet = new HttpGet(url);try { File file = new File(Environment.getExternalStorageDirectory(), fileName); if (!file.exists()) { file.createNewFile(); } else { boolean flag = file.delete(); if (flag) { file.createNewFile(); } else { return; } } RandomAccessFile randomFile = new RandomAccessFile(file, "rw"); HttpResponse response = new DefaultHttpClient(params).execute(httpGet); HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); randomFile.seek(randomFile.length()); byte[] buffer = new byte[1024]; int lenght = 0; while ((lenght = in.read(buffer)) > 0) { randomFile.write(buffer, 0, lenght); DebugTraceTool.debugTraceE(this, "file length == " + randomFile.length()); } randomFile.close(); httpGet.abort(); } catch (Exception e) { e.printStackTrace();}
需要注意的点:
1.需要单启动一个线程,不能在主线程执行文件下载的操作.
2.下载的文件名,长度有限制,推荐文件的名称的长度控制在100.防止出现IOException: open failed: ENAMETOOLONG (File name too long)错误,导致下载的任务无法正常开始. 原因: Java语言规范中对文件名的长度是没有限制的。但是操作系统对文件名的长度有限制,最常见的是255个字节,这个限制长度包括文件名的后缀,如.mp3,.mkv等。
发表评论
最新留言
很好
[***.229.124.182]2025年04月17日 23时01分38秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
08-03 细分构建机器学习应用程序的流程-流程简介
2021-05-09
B-概率论-条件概率
2021-05-09
191107
2021-05-09
191120
2021-05-09
191123
2021-05-09
第4章 字符串、数组和特殊矩阵
2021-05-09
0608-nn和autograd的区别
2021-05-09
MYSQL 数据库结构优化
2021-05-09
leetcode 一些算法题及答案
2021-05-09
spring 整合 ActiveMQ
2021-05-09
PHP 取前一天或后一天、一个月时间
2021-05-09
Kafka 分布式的,基于发布/订阅的消息系统
2021-05-09
Spring Bean的加载
2021-05-09
Web笔记(一) Web 简介与开发环境搭建
2021-05-09
Java基础回顾-缓冲流
2021-05-09
JSONPath小试牛刀之Snack3
2021-05-09
更强的 JsonPath 兼容性及性能测试
2021-05-09
Weed3 for java 新的微型ORM框架
2021-05-09
利用 Solon-web 框架写一个 Hello World
2021-05-09
Solon Ioc 的注解对比Spring及JSR330
2021-05-09